首页 > 其他 > 详细

深拷贝的现代写法

时间:2016-03-26 08:36:25      阅读:222      评论:0      收藏:0      [点我收藏+]

技术分享

#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;
}


本文出自 “言安阳” 博客,谢绝转载!

深拷贝的现代写法

原文:http://iynu17.blog.51cto.com/10734157/1755157

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!