=重载与使用复制构造一样需要重新为对象分配内存,并且需要注意如果对象没有被提前创建而是采用了MySring L=M;的形式系统还是会采用复制构造而不是=重载;
class MyString {
private:
char*str;
int len;
public:
MyString() {};
MyString(const char*str);
void disp();
MyString&operator=(const MyString&S);
void SetStr(int i, char c);
};
void MyString::SetStr(int i, char c)
{
str[i] = c;
}
MyString&MyString::operator=(const MyString&S)
{
if (len < S.len) { len = S.len;delete[]str;str = new char[S.len + 1]; }
int i;
for (i = 0;i < S.len;i++)
str[i] = S.str[i];
str[i] = '\0';
return *this;
}
void MyString::disp()
{
cout << str << endl;
cout << len << endl;
}
MyString::MyString(const char*str)
{
this->str = new char[strlen(str) + 1];
int i;
for (i = 0;i < strlen(str);i++)
(this->str)[i] = str[i];
(this->str)[i] = '\0';
len = strlen(str);
}
int main()
{
MyString S("hello");
MyString M;
M = S;//引用的是=
MyString L = S;//会引用复制构造
cout << "S:";
S.disp();
cout << "M:";
M.disp();
cout << "L:";
L.disp();
M.SetStr(0, 'H');
cout << "S:";
S.disp();
cout << "M:";
M.disp();
cout << "L:";
L.disp();
system("pause");
}