operator++ 中的整数参数 [英] Int Argument in operator++
问题描述
class myClass
{
public:
void operator++()
{
// ++myInstance.
}
void operator++(int)
{
// myInstance++.
}
}
除了让编译器区分 myInstance++
和 ++myInstance
之外,还有 operator++
中的可选 int
参数实际上是为了什么?如果是,那是什么?
Besides letting the compiler distinguish between myInstance++
and ++myInstance
, is the optional int
argument in operator++
actually for anything? If so, what is it?
推荐答案
正如@Konrad 所说,int 参数不用于任何事情,除了区分前增量和后增量形式.
As @Konrad said, the int argument is not used for anything, other than to distingush between the pre-increment and post-increment forms.
但是请注意,您的运算符应该返回一个值.前增量应该返回一个引用,后增量应该返回按值.即:
Note however that your operators should return a value. Pre-increment should return a reference, and post-increment should return by-value. To wit:
class myClass
{
public:
myClass& operator++()
{
// ++myInstance.
return * this;
}
myClass operator++(int)
{
// myInstance++.
myClass orig = *this;
++(*this); // do the actual increment
return orig;
}
};
正如 Gene Bushuyev 在下面正确提到的,operator++
返回非空并不是绝对的要求.但是,在大多数情况下(我想不出例外),您需要这样做.特别是如果您想将运算符的结果分配给某个其他值,例如:
As Gene Bushuyev mentions correctly below, it is not an absolute requirement that operator++
return non-void. However, in most cases (I can't think of an exception) you'll need to. Especially if you want to assign the results of the operator to some other value, such as:
myClass a;
myClass x = a++;
此外,使用 postimcrement 版本,您将在对象递增之前返回对象.这通常是使用本地临时文件完成的.见上文.
Also, with the postimcrement version, you will return the object before it was incremented. This is typically done using a local temporary. See above.
这篇关于operator++ 中的整数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!