[英]Int Argument in operator++
class myClass
{
public:
void operator++()
{
// ++myInstance.
}
void operator++(int)
{
// myInstance++.
}
}
Besides letting the compiler distinguish between myInstance++
and ++myInstance
, is the optional int
argument in operator++
actually for anything? 除了让编译器区分
myInstance++
和++myInstance
, operator++
的可选int
参数实际上是什么? If so, what is it? 如果是这样,它是什么?
As @Konrad said, the int argument is not used for anything, other than to distingush between the pre-increment and post-increment forms. 正如@Konrad所说,除了在增量前和增量后形式之间进行distingush之外,int参数不会用于任何事情。
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;
}
};
As Gene Bushuyev mentions correctly below, it is not an absolute requirement that operator++
return non-void. 正如Gene Bushuyev在下面正确提到的那样,
operator++
返回非空虚并不是绝对的要求。 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++;
Also, with the postimcrement version, you will return the object before it was incremented. 此外,使用postimcrement版本,您将在对象增加之前返回该对象。 This is typically done using a local temporary.
这通常使用本地临时完成。 See above.
往上看。
is the optional int argument in operator++ actually for anything?
实际上对于任何东西都是operator ++中的可选int参数?
No. The only purpose is to distinguish between the two overloads. 不。唯一的目的是区分两个重载。 Quite disappointing, I know.
我知道,非常令人失望。 ;-)
;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.