C++ 赋值运算符重载
类的定义
class Test{
int id;
public:
Test(int i): id(i){
cout << "obj_" << i << " created" << endl;
}
Test& operator= (const Test& right){
if (this == &right){
cout << "same object." << endl;
} else {
cout << "success." << endl;
this->id = right.id;
}
return *this;
}
void print(){
cout << id << endl;
}
};
主函数
int main(){
Test a(1), b(2);
cout << "a = a: ";
a = a;
a.print();
cout << "a = b: ";
a = b;
a.print();
return 0;
}
结果
obj_1 created
obj_2 created
a = a: same object.
1
a = b: success.
2
Listen to your heart.