1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 class String {
 5 public:
 6     String (const char* str = NULL) {
 7         m_str = new char[strlen(str?str:"")+1];
 8         strcpy (m_str, str ? str : "");
 9     }
10     ~String (void) {
11         if (m_str) {
12             delete[] m_str;
13             m_str = NULL;
14         }
15     }
16     String (const String& that) :
17         m_str (strcpy (
18             new char[strlen(that.m_str)+1],
19             that.m_str)) {}
20     /* 菜鸟
21     void operator= (const String& that) {
22         m_str = new char[strlen(that.m_str)+1];
23         strcpy (m_str, that.m_str);
24     }*/
25     String& operator= (const String& that) {
26         if (&that != this) {
27             /* 小鸟
28             delete[] m_str;
29             m_str = new char[strlen(that.m_str)+1];
30             strcpy (m_str, that.m_str);
31             */
32             /* 大鸟
33             char* str = 
34                 new char[strlen(that.m_str)+1];
35             delete[] m_str;
36             m_str = strcpy (str, that.m_str);
37             */
38             // 老鸟
39             String temp (that);
40             swap (m_str, temp.m_str);
41         }
42         return *this;
43     }
44     const char* c_str (void) const {
45         return m_str;
46     }
47     operator const char* (void) const {
48         return c_str ();
49     }
50 private:
51     char* m_str;
52 };
53 int main (void) {
54     String s1 ("Hello, World !");
55     cout << s1.c_str () << endl;
56     String s2 = s1;
57     cout << s2.c_str () << endl;
58     String s3 ("Hello, Linux !");
59     try {
60         s1 = s3;
61     }
62     catch (exception& ex) {
63         cout << ex.what () << endl;
64     }
65     cout << s1.c_str () << endl;
66     const char* psz = s1;
67     cout << s1 << endl;
68     cout << psz << endl;
69     return 0;
70 }

 

posted on 2017-03-14 12:36  北纬395427  阅读(195)  评论(0编辑  收藏  举报