【问题标题】:unary operator overloading special case in c++一元运算符重载C++中的特殊情况
【发布时间】:2012-10-17 01:21:22
【问题描述】:

我成功地完全重载了一元 ++,-- 后缀/前缀运算符,我的代码工作正常,但是当使用 (++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;
   }

有什么解决办法或理由???

【问题讨论】:

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


    【解决方案1】:

    一般来说,预增量应该返回 ABC&amp;,而不是 ABC

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

    【讨论】:

      【解决方案2】:

      我发现最好在前增量方面实现后增量。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        • 2010-10-21
        相关资源
        最近更新 更多