Pergunta

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???

Foi útil?

Solução

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

Outras dicas

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).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top