c++ - C++ 中的一元运算符重载特例

标签 c++ visual-c++ post-increment unary-operator

我成功地完全重载了一元 ++,-- 后缀/前缀运算符并且我的代码工作正常,但是在使用时 (++obj)++声明它返回意外的结果

这是代码

class ABC
{
 public:
    ABC(int k)
    {
        i = k;
    }


    ABC operator++(int )
    {
        return ABC(i++);
     }

     ABC operator++()
     {
        return ABC(++i);
     }

     int getInt()
     {
      return i;
     }
    private:
   int i;
 };

 int main()
 {
    ABC obj(5);
        cout<< obj.getInt() <<endl; //this will print 5

    obj++;
     cout<< obj.getInt() <<endl; //this will print 6 - success

    ++obj;
    cout<< obj.getInt() <<endl; //this will print 7 - success

    cout<< (++obj)++.getInt() <<endl; //this will print 8 - success

        cout<< obj.getInt() <<endl; //this will print 8 - fail (should print 9)
    return 1;
   }

有什么解决办法或者原因吗???

最佳答案

一般情况下,预增量应返回 ABC&,而不是 ABC

您会注意到这会使您的代码无法编译。修复它相对容易(不要创建新的 ABC,只需编辑现有值,然后返回 *this)。

关于c++ - C++ 中的一元运算符重载特例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13092642/

相关文章:

c++ - 为什么 SetWindowsHookEx 不接受钩子(Hook)程序?

javascript - i++ 与 JavaScript for 循环中的++i

c++ - 如果x = 5,那么a =++ x *++ x如何给出49?

c++ - 跨线程调用 a.k.a 从其他线程在主/UI 线程上运行而无需依赖

windows - 如何在 Windows 中以 30 毫秒的间隔执行 10 毫秒 CPU 时间操作?

c++ - 在 windows nts 模式下构建 php 扩展

c++ - C++中如何访问基类的成员变量?

c++ - 为什么教科书更喜欢上下文不变的 "++x"而不是 "x++"?

c++ - [c++]为什么我的类析构函数被调用了两次?

c++ - PC 上的 C++ 和 Arduino 之间的 Sizeof() 区别