The code presented has some problems. Are they:
The return of the allocation operator (operator=
) should be, most of the time overwhelming, *this
. I won’t go into the details of when this might be different, but by the level of the question I would wager that you were wrong to return a reference to another object;
Your code is probably leaking memory. Based on your question I see no point in making an allocation of a new object in the attribute operator;
Within the assignment operator usually the object values outro
are assigned to the object this
. This is as simple as assigning one variable to another: membro = outro.membro
;
That said, I suggest you change your attribution operator code to:
Heap& Heap::operator=(const Heap& outro){
// Aqui você atribui os membros do objeto "outro" aos membros do objeto "this".
membro1 = outro.membro1;
membro2 = outro.membro2;
membro3 = outro.membro3;
membro4 = outro.membro4;
return *this;
}
If you want to pass the responsibility of "copying" the variables of outro
for the method escreve()
there is no problem, but you must pass the reference of the source object. Example:
Heap& Heap::operator=(const Heap& outro){
printf("chamei atribuição\n");
this->escreve(outro);
return *this;
}
Of course for this to work you must first modify or overwrite the method escreve()
that you have already implemented.
PS: The use of "prefix" this->
is optional.
I’m a little rusty on C++ but I don’t think it’s right to return a heap object (allocated with new). What’s more, the idea of returning in Operator= is to return *this. I don’t understand why creating another object.
– epx