String类的编写

String类的编写

1,const & class 可以调用私有成员

2. 友元函数重载

 1 class MyString
 2 {
 3 public:
 4     MyString(char * s = NULL)
 5     {
 6         if(s != NULL)
 7         {
 8             int size = strlen(s) + 1;
 9             m_str = new char[size];
10             strcpy(m_str, s);
11         }
12         else m_str = NULL;
13     }
14     MyString(const MyString & other)
15     {
16         if(other.m_str != NULL)
17         {
18             int size = strlen(other.m_str) + 1;
19             m_str = new char[size];
20             strcpy(m_str,other.m_str);
21         }
22     }
23     MyString & operator = (const MyString & other)
24     {
25         if(m_str == other.m_str)
26             return *this;
27         delete []m_str;
28         if(other.m_str != NULL)
29         {
30             int size = strlen(other.m_str) + 1;
31             m_str = new char[size];
32             strcpy(m_str,other.m_str);
33         }
34         return *this;
35     }
36     ~MyString()
37     {
38         if(m_str != NULL)
39         delete []m_str;
40     }
41     friend ostream & operator<<(ostream &o,const MyString &str)
42     {
43         o << str.m_str ;
44         return o;
45     }
46 private:
47     char * m_str;
48 };

代码。

posted @ 2012-11-12 17:25  可乐爱上了雪碧  阅读(248)  评论(0编辑  收藏  举报