您的位置:首页 > 编程语言 > C语言/C++

C++ 中string类的三种模拟实现方式

2016-06-05 18:37 309 查看
1.原始版本(拷贝构造和赋值运算符重载时,需要重新开辟空间)

[code=cpp;toolbar:false">#include <iostream>
#include <string>

using namespace std;

class String
{
friend ostream& operator<<(ostream& os, const String& S);
public:
String(char* str = "")
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
String(const String& S)
:_str(new char[strlen(S._str)+1])
{
strcpy(_str, S._str);
}
String& operator=(const String& S)
{
if(_str != S._str)
{
delete[] _str;
_str = new char[strlen(S._str)+1];
strcpy(_str, S._str);
}
return *this;
}
~String()
{
if(_str != NULL)
{
delete[] _str;
}
}

private:
char* _str;
};

ostream& operator<<(ostream& os, const String& S)
{
os<<S._str;
return os;
}

int main()
{
String s1("abcde");
cout<<s1<<endl;
String s2(s1);
cout<<s2<<endl;
String s3;
cout<<s3<<endl;
s3 = s2;
cout<<s3<<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: