String类的构造函数,析构函数,赋值函数

View Code
 1 #include<string.h>
2 class String
3 {
4 private:
5 char * m_data;
6 public:
7 String(const char *str = NULL);//构造函数
8 String(const String &other);//拷贝构造函数
9 ~String(void);//析构函数
10 String &operator = (const String &other);//赋值函数
11 }
12
13 String::String(const char *str)
14 {
15 if(str == NULL)//当串不存在的时候,申请一个空间存放'\0'
16 {
17 m_data = new char[1];
18 *m_data = '\0';
19 }
20 else //当串存在的时候,申请同样大小的空间,将串复制到m_data
21 {
22 int len = strlen(str);
23 m_data = new char[len + 1];
24 strcpy(m_data, str);
25 }
26 }
27 String::String(const String &other)
28 {
29 if(m_data != NULL)//如果m_data不为空,删除原来空间,重新申请
30 delete[] m_data;
31 int len = strlen(other.m_data);
32 m_data = new char[len + 1];
33 strcpy(m_data,other.m_data);
34 }
35 String & String::operator=(const String &other)
36 {
37 if(this == &other)//如果地址相同,直接返回,即自赋值
38 return *this;
39 delete[] m_data;//否则,删除原来空间,重新构造
40 int len = strlen(other.m_data);
41 m_data = new char[len + 1];
42 strcpy(m_data, other.m_data);
43 return *this;
44 }
45 String::~String()
46 {
47 delete[] m_data;//释放空间
48 }
49 String::ShowString()
50 {
51 cout << this.m_data << endl;//m_data为类的私有成员,通过类的public成员函数访问
52 }
53
54 void main()
55 {
56 String A;
57 char *p = "abcdefg";
58 String B(p);
59 A.ShowString();
60 A = B;
61 A.ShowString();
62 }

抄自:http://www.cnblogs.com/Laokong-ServiceStation/archive/2011/04/19/2020402.html

and,谢谢你的http://man.chinaunix.net/呵呵

原文地址:https://www.cnblogs.com/mrpomelo/p/2221016.html