1 #define _CRT_SECURE_NO_WARNINGS
2 #include <iostream>
3 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<class T>
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<mystring>(str1, str2).pstr << endl;
77 cin.get();
78 }