#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<cstring> using namespace std; class mystring { public: char *p; int n; mystring() :p(nullptr), n(0) { } mystring(char *p) { this->n = strlen(p) + 1; this->p = new char[this->n]; strcpy(this->p, p); } mystring(const mystring&str) { cout << "深拷贝" << endl; this->n = strlen(str.p) + 1; this->p = new char[this->n]; strcpy(this->p, str.p); } mystring operator+(const mystring&str) { cout << "赋值+重载" << endl; mystring tmp; tmp.n = this->n+strlen(str.p) + 1; tmp.p = new char[tmp.n]; strcpy(tmp.p, this->p); strcat(tmp.p, str.p); return tmp; } mystring &operator=(const mystring&str) { cout << "赋值=重载" << endl; char *old = str.p; this->n = strlen(str.p) + 1; this->p = new char[this->n]; strcpy(this->p, str.p); return *this; } ~mystring() { delete[]p; } }; int main() { mystring str1("hello"); mystring str2("world"); mystring str3 = str1 + str2; mystring str4(str1 + str2); cout << str3.p << endl; cout << str4.p << endl; mystring str5; str5 = str1 + str2; cout << str5.p << endl; cin.get(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-34201.html