Operador de incremento posterior para el comportamiento de tipos definidos por el usuario

I was going through some book and I decided to write my own implementation of post-increment operator for user defined type. Here is the code.

#include <iostream>

using namespace std;

class X
{
    int a;

    public:
    X(int x=1):a(x){}

    X operator++(int)
    {
        X oldobj = *this;
        (*this).a++;
        return oldobj;
    }

int get(){return a;}

};

int main()
{
    X obj,obj2;
    obj++ = obj2;
    cout<< obj.get() << endl;
    return 0;
}   

Esperaría que la salida fuera 1 since obj2's value will be copied after the increment is done. But the output was 2.

Pensamientos

P.S. I know this code will not win any medals and its fallacies. It is just for my understanding. Incidentally, ++obj = obj2 devoluciones 1;

Is the behavior undefined?

preguntado el 08 de noviembre de 11 a las 09:11

(*this).a++ is more usually written as this->a++ (o solo a++) -

3 Respuestas

As your syntax tells you, the postfix operator returns a copy of the old value, so that's what gets incremented, not your object.

Básicamente,

obj++ = obj2;

Will do this:

X tempObj = obj;
obj ++;
tempObj = obj2;

Estas asignando obj2 to a temporary variable.

respondido 08 nov., 11:14

obj++ returns a temporary object holding the old value.

So, although "obj2's value will be copied after the increment is done" is true, it's not copied into the original obj en absoluto :)

respondido 08 nov., 11:14

The behaviour is actually well-defined.

You are assigning to the result of obj++, which is a temporary - a copy of obj from before the post-increment. This assignment does not affect obj, which retains its value of 2 from the increment.

El código es aproximadamente equivalente a:

X temp = obj;
obj++;
temp = obj2;

respondido 08 nov., 11:14

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.