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

String的深拷贝

时间:2015-08-29 17:07:16      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:string的深拷贝

#include<iostream>

using namespace std;

class String

{

public:

char* GetChar()

{

return _ptr;

}

void swap(String&s)

{

char* tmp = s._ptr;

s._ptr = _ptr;

_ptr = tmp;

}

String(char*str)

:_ptr(new char[strlen(str) + 1])

{

strcpy(_ptr, str);

}

String(const String&s)

:_ptr(NULL)

    {

String tmp(s._ptr);

swap(tmp);


}

String& operator=(const String&s)

{

if (this != &s)

{

String tmp(s._ptr);

swap(tmp);

}

return *this;

}

~String()

{

if (_ptr)

{

delete[]_ptr;

}

}


private:

char* _ptr;

};

int main()

{

String s1("abcd");

String s2(s1);

String s3("efghs");

s3 = s2;

cout<< "s1:" << s1.GetChar() << endl;

cout<< "s2:" << s2.GetChar() << endl;

cout << "s3:" << s3.GetChar() << endl;

return 0;

}


String的深拷贝

标签:string的深拷贝

原文地址:http://10622551.blog.51cto.com/10612551/1689550

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