【c++】简单的string类的几个基本函数

// string的几个基本函数的实现

#include <iostream>
#include <assert.h>
#include <string.h>
using namespace std;

class String
{
public:
	String()
	{
		_str = new char[1];
		_str[0] = '';
	}
	String(char *str)
	{
		assert(str != NULL);
		_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 (this != &s)
		{
			delete[] _str;
			_str = new char[strlen(s._str) + 1];
			strcpy(_str, s._str);
		}
		return *this;
	}
	~String()
	{
		delete[] _str;
	}
public:
	void getstr()
	{
		cout << _str << endl;
	}
private:
	char *_str;
};

int main()
{
	String s;
	s.getstr();
	String s1("123");
	s1.getstr();
	String s2 = s1;
	s2.getstr();
	s = s1;
	s.getstr();
	return 0;
}






原文地址:https://www.cnblogs.com/yfceshi/p/7130686.html