深拷貝的現代寫法

wKioL1b0wXzBjJphAABE5Xm1wLU459.png

#include<iostream>
using namespace std;

class String
{
public:
           String(char * str="")          //不能strlen(NULL)
                    :_str(new char [strlen(str ) + 1])
           {
                    strcpy(_str, str);
           }
           String(const String &s)
                    :_str(NULL )
           {
                    String tmp(s ._str);
                    swap(_str,tmp._str);
           }
           //String& operator=(const String& s)
           //{
           //   if (this != &s)
           //   {
           //       String tmp(s._str);
           //       swap(_str, tmp._str);
           //   }
           //   return *this;
           //}

           String& operator=(String s)  //優化 (s不能加引用,否則會改變實參的值)(這裏的s是實參的一份拷貝)
           {
                    swap(_str, s._str);
                    return *this ;
           }
           char* CStr()
           {
                    return _str;
           }
           ~String()
           {
                    delete[] _str;
           }
private:
           char* _str;
};

void Test()
{
           String s1("aaaaa" );
           cout << s1.CStr() << endl;
           String s2(s1);
           cout << s2.CStr() << endl;
           String s3 = s1;
           s3= s2;
           cout << s3.CStr() << endl;
           String s4;
           // s4 = s1;
           cout << s4.CStr() << endl;
          
}
int main()
{
           Test();
           system("pause" );
           return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章