c++中string类的实现
今天面试被考到了, 全给忘记了!!!
 
//string类的实现
#include <iostream>
#include <string.h>
using namespace std;

class String{
public:
	//构造函数
	String(const char *str = ""):
		m_str(strcpy(new char[strlen(str)+1],str)){}
	//析构函数
	~String(void){
		delete[] m_str;
		m_str = NULL;
	}
	//深拷贝构造
	String(const String &that):
		m_str(strcpy(new char[strlen(that.m_str)+1],that.m_str)){}

	//拷贝赋值
	String &operator = (const String &that){
		if(&that != this){
/*			小鸟版
			delete[] m_str;
			m_str = new char[strlen(that.m_str)+1];
			strcpy(m_str,that.m_str);
*/
			char *str = new char[strlen(that.m_str)+1];
			delete[] m_str;
			m_str = strcpy(str,that.m_str);
/*
			老鸟版
			String temp(that);
			swap(m_str,that.m_str);
*/
		}
		return *this;
	}
	const char *c_str(void)const{
		return m_str;
	}
private:
	char *m_str;
};

int main(){
	String s1("hello,world!");
	cout << s1.c_str() << endl;

	String s2 = s1;//拷贝构造
	cout << s2.c_str() << endl;

	String s3("hello C++");
	s2 = s3;
	cout << s2.c_str() << endl;
	return 0;
}