C ++运算符重载前缀/后缀

时间:2013-06-20 22:10:45

标签: c++ operator-overloading postfix-operator prefix-operator

我正在学习C ++中的运算符重载。原始后缀++具有优先级低于赋值运算符的属性。例如,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();
}

输出(0,0)(2,2),而我期望(0,0)(1,1)。

你能帮助我理解为什么会这样,以及恢复原有财产的可能性吗?

2 个答案:

答案 0 :(得分:4)

它打印(0,0)(2,2),因为您的运算符++与内置运算符V一样,在递增 之后,会返回对象的副本而不是之前。

当您重载操作符时,这完全在您的控制之下,因此您有责任使其在这方面的行为类似于相应的内置运算符。

这是您可以重写运算符以实现该目标的方法:

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!
}

这是live example

答案 1 :(得分:1)

在递增之前,您需要制作vec[0]vec[1]的副本,而不是之后。那样return v将返回原始值而不是递增值。

V operator++(int dummy)
{
    V v(vec[0],vec[1]);
    for(int i=0; i<2; i++)
    {
        ++vec[i];
    }
    return v;
}