String类原型:
1 Class String
2 {
3 Public:
4 String(const char *str);
5 String(const String &other);
6 ~String(void);
7 String& operator =(const String &other);
8 Private:
9 char *m_data;
10 };
String的析构函数
1 String::~String(void)
2 {
3 delete []m_data; //由于m_data是内部数据,也可以写成delete m_data;
4 }
String的构造函数
1 String::String(const char *str)
2 {
3 if(str==NULL)
4 {
5 m_data = new char[1];
6 *m_data = '\0';
7 }
8 else
9 {
10 int length = strlen(str);
11 m_data = new char[length+1];
12 strcpy(m_data, str);
13 }
14 }
String的拷贝构造函数
1 String::String(const String &other)
2 {
3 int length = strlen(other.m_data);
4 m_data = new char[length+1];
5 strcpy(m_data, other.m_data);
6 }
String的拷贝赋值函数
1 String& String::operator =(const String &other)
2 {
3 if(this==&other)
4 return *this;
5 int length = strlen(other.m_data);
6 char *temp = new char[length+1];
7 if(temp!=NULL)
8 {
9 strcpy(temp, other.m_data);
10 delete []m_data;
11 m_data = temp;
12 }
13 return *this;
14 }