Appearance
拷贝赋值函数
- 拷贝构造函数用在初始化,拷贝赋值用在赋值,本质是
=运算符的重载
cpp
string s1("hello world");
// 以下是拷贝赋值构造函数的调用
string s2; // 这里初始化一个对象
s2 = s1;格式
- 函数名:
operator= - 返回值:该左操作数自身的引用
- 参数其他同类对象的引用
- 权限
public - 默认提供的拷贝是浅拷贝,即拷贝地址
cpp
Stu & operator=(const Stu &other) {
if(this != &other) {
this->age = other.age;
this->name = other.name;
this->score = new double(*(other.score));
}
return *this; // 指针的值,为左值
}