视觉上的一元操作员在C 中超载特殊情况

visual unary operator overloading special case in c++

本文关键字:中超 超载 情况 操作员 一元 视觉上      更新时间:2023-10-16

我的成功完全超载了Unary ++,-- Postfix/prefix 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)。

我发现最好以插入后实施插入后。

ABC operator++(int )
{
   ABC result(*this);
   ++*this; // thus post-increment has identical side effects to post-increment
   return result; // but return value from *before* increment
}
ABC& operator++()
{
   ++i; // Or whatever pre-increment should do in your class
   return *this;
}