1.拷貝構造(深拷貝) :用已經有的對象構造一個新對象
MyString::MyString(const MyString & other)
{
int len = strlen(other._str);
this->_str = new char[len+1];
strcpy(this->_str,other._str);
}
MyString s1;
MyString s2(s1); //調用了拷貝構造
MyString s2=s1; //調用了拷貝構造
2 .賦值運算符重載(注意有返回值,即對象本身的引用):用已經有的對象賦值另一個已有對象
MyString & MyString::operator=(const MyString & another)
{
if(this == &another)
return *this;
else
{
delete []this->_str;
int len = strlen(another._str);
this->_str = new char[len+1];
strcpy(this->_str,another._str);
return *this;
}
}
MyString s1;
MyString s2;
s2=s1; //調用賦值運算符重載
3 .返回棧上的對象而不是引用(例外:可以返回對象本身的this引用)