ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码

C++ 中string类的三种模拟实现方式(1/2)

来源:网络整理     时间:2016-04-01     关键词:

本篇文章主要介绍了"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<<><><><>

测试结果:

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

2.引用计数方式(拷贝构造时和赋值运算符重载时,只需对其引用计数器操作)

相关图片

相关文章