“=”只能重载成成员函数
- 返回值是一个引用
class String {
private:
char * str;
public:
String():str(new char[1]) { str[0] = 0; }
const char * c_str() { return str; }
String & operator = (const char * s);
String::~String() { delete []str; }
};
String & String::operator = (const char* s) {
delete []str;
str = new char[strlen(s)+1];
strcpy(str, s);
return *this;
}
main() {
String s;
s = "luck"; // 等价于 s.operator=("luck");
cout << s.c_str() << endl;
// String s2 = "hello"; // 出错!初始化语句,不是赋值语句
}
浅拷贝和深拷贝
同样还是上面的String类,如果调用如下语句,则是浅拷贝,会产生隐患String s1, s2;
S1 = "this";
S2 = "that";
S1 = S2;
- 返回值是一个引用
二者的指针指向同一片地址,同时S1的指针原本指向的内存也没有被释放。两个对象消亡后,会delete两次指针
- 对S1再次赋值,S2的内容也被更改
如果是执行语句 S1 = S1 呢?
改进如下,进行重载
String & String::operator = (const String & s) {
if(this == &s)
return *this;
delete []str;
str = new char[strlen(s)+1];
strcpy(str, s);
return *this;
}