实现String

 1 class String
 2 {
 3 public:
 4     //构造函数
 5     String(const char* str = NULL) {
 6         m_str = new char[strlen(str ? str : "") + 1];
 7         strcpy(m_str, str ? str : "");
 8     }
 9     //析构函数
10     ~String(void) {
11         if (m_str) {
12             //cout << "析构函数:" << (void*)m_str << endl;
13             delete[] m_str;
14             m_str = NULL;
15         }
16     }
17     //拷贝构造(深拷贝)
18     String(const String& that) {
19         m_str = new char[strlen(that.m_str)+1];
20         strcpy(m_str, that.m_str);
21     }
22     //拷贝赋值(深拷贝)
23     String& operator=(const String& that) {
24         if (&that != this) {
25             delete[] m_str;
26             m_str = new char[strlen(that.m_str) + 1];
27             strcpy(m_str, that.m_str);    
28             //复用拷贝构造版
29             /*String tmp(that);
30             swap(m_str,tmp.m_str*/ 
31         }
32         return *this;
33     }
34 public:
35     void print(void)const {
36         cout << m_str << endl;
37     }
38 private:
39     char* m_str;
40 };

 

posted @ 2021-09-24 10:05  盾牌座UY  阅读(37)  评论(0)    收藏  举报