天天看点

重载赋值运算符

StringBad class2("abc");

StringBad class1 = class2;

出现语句2赋值过程有两种:

1.调用拷贝构造函数。

2.创建临时对象,通过赋值,将临时对象的值赋给新对象。

情况2:需要编写赋值运算符

StringBad & StringBad::operator=(const StringBad & st)

{

if(this == &st)

return *this;

delete[] str;

len = st.len;

str = newchar[len+1];

strcpy(str,st.str);

return *this;

}