String类简单了解

 

 

 1 #include <stdio.h>
2 #include <string.h>
3
4 class String
5 {
6 public:
7 String(const char *str = NULL);
8 ~String();
9 String(const String &other);
10 String& operator = (const String &other);
11 private:
12 char *m_data;
13 };
14
15 String::~String()
16 {
17 delete [] m_data;
18 }
19
20 String::String(const char *str)
21 {
22 if (!str)
23 {
24 m_data = new char[1];
25 m_data[0] = '\0';
26 }
27 else
28 {
29 int len = strlen(str);
30 m_data = new char[len + 1];
31 strcpy(m_data, str);
32 }
33 }
34
35 String::String(const String& other)
36 {
37 /*
38 if (!other)
39 {
40 m_data = new char[1];
41 m_data = '\0';
42 }
43 else
44 {
45 */
46 delete m_data;
47 int len = strlen(other.m_data);
48 m_data = new char[len + 1];
49 strcpy(m_data, other.m_data);
50
51 //}
52 }
53
54 String & String::operator=(const String& other)
55 {
56 if (this == &other)
57 {
58 return *this;
59 }
60 else
61 {
62 delete m_data;
63 int len = strlen(other.m_data);
64 m_data = new char[len + 1];
65 strcpy(m_data, other.m_data);
66 return *this;
67 }
68 }
69
70
71 int main()
72 {
73
74 return 0;
75 }

 

posted @ 2011-11-09 11:08  Clin  阅读(153)  评论(0编辑  收藏  举报