參考:https://www.cnblogs.com/codingmengmeng/p/5871254.html
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class String
{
private:
char *str;
int len;
public:
String(const char* s);//構造函數的申明
String operator=(const String& another);
void show()
{
cout << "value =" << str << endl;
}
String(const String& another)
{
len = another.len;
str = new char[len + 1];
strcpy(str, another.str);
cout << "拷貝構造函數" << endl;
}
~String()
{
delete[] str;
cout << "析構函數" << endl;
}
};
String::String(const char*s)
{
cout << "構造函數" << endl;
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
String String::operator=(const String &another)
{
if (this==&another)
{
return *this;
}
delete[] str;
len = another.len;
str = new char[len + 1];
strcpy(str,another.str);
return *this;
}
int main()
{
String str1("china");
String str2("tianjin");
String str3("wuhu");
str1.show();
str2.show();
str3.show();
(str3 = str1) = str2;//str3.operator=(str1.operator=(str2))
str3.show();
str1.show();
return 0;
}