一元运算符在c ++中重载特殊情况

Sou*_*abh 3 c++ unary-operator visual-c++ post-increment

我成功完全重载了一元++,--postfix /前缀运算符,我的代码工作正常,但在使用(++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;
   }
Run Code Online (Sandbox Code Playgroud)

有任何解决方案或原因???

Yak*_*ont 7

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

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