1 #define _CRT_SECURE_NO_WARNINGS 2 #include3 using namespace std; 4 5 class mystring 6 { 7 public: 8 char *pstr; 9 int length;10 mystring():pstr(nullptr),length(0)11 {12 13 }14 15 mystring(char *str)16 {17 //获取字符串长度18 this->length = strlen(str) + 1;19 this->pstr = new char[this->length + 1];20 //拷贝21 strcpy(this->pstr, str);22 }23 24 //拷贝构造25 mystring(const mystring &my)26 {27 this->length = my.length;28 this->pstr = new char[this->length];29 strcpy(this->pstr, my.pstr);30 }31 32 mystring add(const mystring &my)33 {34 int n = this->length + my.length - 1;35 mystring temp;36 temp.length = n;37 //分配内存38 temp.pstr = new char[temp.length];39 strcpy(temp.pstr, this->pstr);40 //尾部添加41 strcat(temp.pstr, my.pstr);42 return temp;43 }44 45 //重载加法46 mystring operator +(const mystring &my)47 {48 int n = this->length + my.length - 1;49 mystring temp;50 temp.length = n;51 //分配内存52 temp.pstr = new char[temp.length];53 strcpy(temp.pstr, this->pstr);54 //尾部添加55 strcat(temp.pstr, my.pstr);56 return temp;57 }58 };59 60 template 61 T add(T a, T b)62 {63 return a + b;64 }65 66 void main()67 {68 mystring str1 = "hello";69 mystring str2 = "world";70 //mystring str3 = str1.add(str2);71 //mystring str3 = str1 + str2;72 mystring str3 = str1.operator+(str2);73 cout << str3.pstr << endl;74 75 //模板与运算符重载76 cout << add (str1, str2).pstr << endl;77 cin.get();78 }