c++中赋值运算符重载为什么要用引用做返回值?
class string{
public:
string(const char *str=NULL);
string(const string& str); //copy构造函数的参数为什么是引用呢? 我相信大家都懂的!
string& operator=(const string & str); //赋值函数为什么返回值是引用呢?
~string();
};
如果返回值时, return *this后马上就调用拷贝构造函数。
但是万一由于没有定义拷贝构造函数 ,就会调用默认的拷贝构造函数。
我们知道调用默认的拷贝构造函数时当在类中有指针时就会出错(浅拷贝)。
所以如果你不用引用做返回时 就必须定义自定义的拷贝构造函数。
当然咯 有指针成员时 必须要注意 自定义 拷贝构造了
其实还是为了提高效率 和 减少零时对象的生成 不调用 拷贝构造函数!
class MyClass {
public:
// 赋值运算符重载
MyClass& operator=(const MyClass& other) {
if (this != &other) { // 自赋值检查
// 执行赋值操作
// ...
}
return *this; // 返回对当前对象的引用
}
};
int main() {
MyClass a, b, c;
a = b = c; // 连续赋值
(a = b).someMethod(); // 链式操作
return 0;
}