简体   繁体   中英

unary operator overloading special case in c++

I have success fully overloaded unary ++,-- postfix/prefix operator and my code works fine, but when ever in use (++obj)++ statement it returns unexpected result

here is code

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

have any solution or reason???

Preincrement should return an ABC& , not an ABC , in general.

You'll note that this will make your code fail to compile. Fixing that is relatively easy (don't create a new ABC , simply edit the existing one's value, then return *this ).

I find it best to implement post-increment in terms of pre-increment.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM