[英]C++ operator overloading prefix/suffix
I'm learning operator overloading in C++. 我正在学习C ++中的运算符重载。 The original suffix ++ has the property that it has lower precedence than the assignment operator.
原始后缀++具有比赋值运算符优先级低的属性。 So for example,
int i=0, j=0; i=j++; cout<<i<<j
因此,例如
int i=0, j=0; i=j++; cout<<i<<j
int i=0, j=0; i=j++; cout<<i<<j
int i=0, j=0; i=j++; cout<<i<<j
will output 01. But this property seems to be lost when I overload the postfix ++. int i=0, j=0; i=j++; cout<<i<<j
将输出01。但是当我重载postfix ++时,此属性似乎丢失了。
#include<iostream>
using namespace std;
class V
{
public:
int vec[2];
V(int a0, int a1)
{
vec[0]=a0;vec[1]=a1;
}
V operator++(int dummy)
{
for(int i=0; i<2; i++)
{
++vec[i];
}
V v(vec[0],vec[1]);
return v;
}
V operator=(V other)
{
vec[0]=other.vec[0];
vec[1]=other.vec[1];
return *this;
}
void print()
{
cout << "(" << vec[0] << ", " << vec[1] << ")" << endl;
}
};
int main(void)
{
V v1(0,0), v2(1,1);
v1.print();
v1=v2++;
v1.print();
}
outputs (0,0)(2,2) while I expected (0,0)(1,1). 输出(0,0)(2,2)而我期望(0,0)(1,1)
Can you help me understand why it's like this, and any possibility of restoring the original property? 您能帮助我理解为什么会这样,以及恢复原始财产的任何可能性吗?
It prints (0,0)(2,2)
because your operator ++
, unlike the built-in one, returns a copy of the V
object it acts upon after incrementing it, rather than before. 之所以打印
(0,0)(2,2)
是因为您的运算符++
与内置的++
不同,它会在递增操作后而不是之前返回它所作用的V
对象的副本。
This is completely under your control when you overload an operator, so it is your responsibility to make it behave like the corresponding built-in operator in this respect. 重载运算符时,这完全在您的控制之下,因此,在这方面,有责任使其像相应的内置运算符一样工作。
This is how you could rewrite your operator to achieve that goal: 这是您可以重写操作员以实现该目标的方式:
V operator++(int dummy)
{
V v(vec[0],vec[1]); // Make a copy before incrementing: we'll return this!
for(int i=0; i<2; i++)
{
++vec[i];
}
return v; // Now this is *not* a copy of the incremented V object,
// but rather a copy of the V object before incrementing!
}
Here is a live example . 这是一个生动的例子 。
You need to make a copy of vec[0]
and vec[1]
before you increment them, not after. 您需要在增加
vec[0]
和vec[1]
之前而不是之后复制它们。 That way return v
will return the original values rather than the incremented ones. 这样,
return v
将返回原始值,而不是递增的值。
V operator++(int dummy)
{
V v(vec[0],vec[1]);
for(int i=0; i<2; i++)
{
++vec[i];
}
return v;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.