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

实现最简单的string类的深拷贝

时间:2015-12-01 01:52:02      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:string类深拷贝

#include<iostream>
using namespace std;

class String
{
public:
                String()
                                :_str( new char [1])
                {
                                _str = ‘\0‘;
                }
                String( const char * str)
                                :_str( new char [strlen(str) + 1])
                {
                                strcpy( this->_str ,str);
                }
                String( const String& str)
                                :_str( new char [strlen(str._str) + 1])
                {
                                strcpy( this->_str ,str._str);
                }
                ~String()
                {               
                                 delete []_str;
                }
                String& operator= (const String& str)
                {
                                String tmp(str);
                                swap( this->_str ,tmp._str );
                                 return *this ;
                }
                 void Display()
                {
                                printf( "%s\n",_str);
                }
private:
                 char *_str;
};

void test1()
{
                String s1( "change world");//构造
                s1.Display();
                String s2 = s1; //拷贝构造
                s2.Display();
                String s3;
                s3.Display();
                s3 = s1; //赋值拷贝
                s3.Display();
}

int main()
{
                test1();
                system( "pause");
                return 0;
}


实现最简单的string类的深拷贝

标签:string类深拷贝

原文地址:http://green906.blog.51cto.com/10697569/1718328

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