String类实现参考c++primer
1 //代码参考C++primer.
2
3
4
5 #include<iostream>
6
7 using namespace std;
8
9
10
11 class String{
12
13 friend ostream& operator<< (ostream&,String&);
14
15 public:
16
17 String(const char* str=NULL); //赋值构造兼默认构造函数(char)
18
19 String(const String &other); //赋值构造函数(String)
20
21 String& operator=(const String&other); //operator=
22
23 String operator+(const String &other)const; //operator+
24
25 bool operator==(const String&); //operator==
26
27 char& operator[](unsigned int); //operator[]
28
29 size_t size(){return strlen(m_data);};
30
31 ~String(void) {delete[] m_data;}
32
33 private:
34
35 char *m_data;
36
37 };
38
39 inline String::String(const char* str)
40
41 {
42
43 if (!str) m_data=0;
44
45 else
46
47 {
48
49 m_data = new char[strlen(str)+1];
50
51 strcpy(m_data,str);
52
53 }
54
55 }
56
57 inline String::String(const String& other)
58
59 {
60
61 if(!other.m_data) m_data=0;
62
63 else
64
65 {
66
67 m_data=new char[strlen(other.m_data)+1];
68
69 strcpy(m_data,other.m_data);
70
71 }
72
73 }
74
75 inline String& String::operator=(const String& other)
76
77 {
78
79 if (this!=&other)
80
81 {
82
83 delete[] m_data;
84
85 if(!other.m_data) m_data=0;
86
87 else
88
89 {
90
91 m_data = new char[strlen(other.m_data)+1];
92
93 strcpy(m_data,other.m_data);
94
95 }
96
97 }
98
99 return *this;
100
101 }
102
103 inline String String::operator+(const String &other)const
104
105 {
106
107 String newString;
108
109 if(!other.m_data)
110
111 newString = *this;
112
113 else if(!m_data)
114
115 newString = other;
116
117 else
118
119 {
120
121 newString.m_data = new char[strlen(m_data)+strlen(other.m_data)+1];
122
123 strcpy(newString.m_data,m_data);
124
125 strcat(newString.m_data,other.m_data);
126
127 }
128
129 return newString;
130
131 }
132
133 inline bool String::operator==(const String &s)
134
135 {
136
137 if ( strlen(s.m_data) != strlen(m_data) )
138
139 return false;
140
141 return strcmp(m_data,s.m_data)?false:true;
142
143 }
144
145 inline char& String::operator[](unsigned int e)
146
147 {
148
149 if (e>=0&&e<=strlen(m_data))
150
151 return m_data[e];
152
153 }
154
155 ostream& operator<<(ostream& os,String& str)
156
157 {
158
159 os << str.m_data;
160
161 return os;
162
163 }
164
165 int main()
166
167 {
168
169 String str1="Hello!";
170
171 String str2="Teacher!";
172
173 String str3 = str1+str2;
174
175 cout<<str3<<"\n"<<str3.size()<<endl;
176 return 0;
177 }