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

标签 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)。

你能帮我理解为什么会这样,有没有可能恢复原来的属性(property)?

最佳答案

它打印 (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 .

关于C++ 运算符重载前缀/后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17224735/

相关文章:

c++ - 从具有非虚拟父类的虚拟类继承的正确方法(续)

C++ LNK2001 尝试使用外部变量时出错

c++ - C++ 编译器会优化按值返回代码吗?

c++ - 如何确定从类模板继承的模板参数的底层模板类型?

c - 如何用优先表证明 C 后缀增量运算符的合理性?

c - 关于 while 循环的表达式

c++ - 实现 C++ 后缀增量运算符

c++ - 如何让编译器知道调用哪个函数重载以避免歧义?

c++ - 在数值表达式中最方便地使用数值包装类的选项有哪些?

C++ - 根据赋值侧重载 [] 运算符