1 #include <iostream>
2 #include <cstring>
3 using namespace std;
4
5
6 class CString {
7 private:
8 char* m_pdata;
9 public:
10 CString(const char* ptr = nullptr) {
11 if (ptr == nullptr) m_pdata = nullptr;
12 m_pdata = new char[strlen(ptr) + 1];
13 strcpy(m_pdata, ptr);
14 }
15 CString(const CString& a) {
16 if (a.m_pdata == nullptr) this->m_pdata = nullptr;
17 this->m_pdata = new char[strlen(a.m_pdata) + 1];
18 strcpy(this->m_pdata, a.m_pdata);
19 }
20
21 CString(CString&& a){
22 this->m_pdata = a.m_pdata;
23 a.m_pdata = nullptr;
24 }
25
26 ~CString() {
27 if (this->m_pdata){
28 delete[] this->m_pdata;
29 }
30 }
31
32 CString& operator=(const CString& a) {
33 if (this == &a)
34 return *this;
35
36 if (this->m_pdata)
37 delete[] this->m_pdata;
38 this->m_pdata = new char[strlen(a.m_pdata) + 1];
39 strcpy(this->m_pdata, a.m_pdata);
40 return *this;
41 }
42
43 CString operator+=(const CString& a) {
44 if (a.m_pdata == nullptr) {
45 return *this;
46 } else if (this->m_pdata == nullptr) {
47 return a;
48 } else {
49 char* tmp = this->m_pdata;
50 this->m_pdata = new char[strlen(this->m_pdata) + strlen(a.m_pdata)
51 + 1];
52 strcpy(this->m_pdata, tmp);
53 strcat(this->m_pdata, a.m_pdata);
54 delete[] tmp;
55 return *this;
56 }
57 }
58
59 friend CString operator+(const CString& a, const CString& b) {
60 char* res = new char[strlen(a.m_pdata) + strlen(b.m_pdata) + 1];
61 strcpy(res, a.m_pdata);
62 strcat(res, b.m_pdata);
63 CString cs(res);
64 delete[] res;
65 return cs;
66 }
67
68 friend ostream& operator<<(ostream& os, const CString& a) {
69 os << a.m_pdata;
70 return os;
71 }
72 };
73
74 int main() {
75
76 CString a("abc");
77 CString b(a);
78 a = b;
79 a += b;
80 CString c = a + b;
81 std::cout << c << std::endl;
82 std::cout << a << std::endl;
83
84 return 0;
85 }