码迷,mamicode.com
首页 > 其他好文 > 详细

深拷贝的现代写法

时间:2016-03-26 08:39:43      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:深拷贝   string类   面试题   

技术分享

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


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

深拷贝的现代写法

标签:深拷贝   string类   面试题   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!