I got stuck with operator assignment problem - it doesn't work as expected. Here's the example code:
#include <iostream>
class TestClass{
private:
int pop;
public:
TestClass(){
std::cout<<"Default Constuctor\n";
}
TestClass(int i):pop(i){
std::cout<<"Param Constuctor\n";
}
TestClass &operator=(const TestClass &other){
std::cout<<"Assignment Operator \n";
return *this;
}
friend std::ostream &operator<<(std::ostream &out, TestClass &x);
};
std::ostream &operator<<(std::ostream &out, TestClass &x){
out<<" This is the TestClass with pop=" << x.pop <<"\n";
return out;
}
int main()
{
TestClass P0(333);
TestClass P_foo(555);
P_foo = P0;
std::cout << P0;
std::cout << P_foo;
return 0;
}
The result of this program is
Param Constuctor
Param Constuctor
Assignment Operator
This is the TestClass with pop=333
This is the TestClass with pop=555
So P_foo
object preserves the initialized value 555. If I comment out my custom assignment operator, the program works as expected.
Param Constuctor
Param Constuctor
This is the TestClass with pop=333
This is the TestClass with pop=333
What's wrong with my assignment operator function?
Aucun commentaire:
Enregistrer un commentaire