首页 > 其他 > 详细

String的深拷贝

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

#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的深拷贝

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

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