本篇文章主要介绍了"C++ 中string类的三种模拟实现方式",主要涉及到方面的内容,对于C/C++jrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播感兴趣的同学可以参考一下:
1.原始版本(拷贝构造和赋值运算符重载时,需要重新开辟空间)#include
#include u...
1.原始版本(拷贝构造和赋值运算符重载时,需要重新开辟空间)
#include
#include
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<<><><><>
测试结果:
![9NS]J@WUEJK%{OZF8AJHC8M.png C++ 中string类的三种模拟实现方式](/imagecaealtourcom/Article/image/20160401/20160401095031_2671.png)
2.引用计数方式(拷贝构造时和赋值运算符重载时,只需对其引用计数器操作)