[C++] String类的复制控制的实现

#include <iostream>
#include <cstring>
using namespace std;

class String { // 一切都是深拷贝!
private :
	char *m_data;
public :
	String(const char *str = NULL);
	String(const String&);
	String& operator =(const String& rhs);
	~String();
	void show() {
		cout << m_data << endl;
	}
};
String::String(const char *str) { // 记住这里你是不能写 m_data = str, 不用犯这种想当然的错误!
	if(str == NULL) {
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		int len = strlen(str);
		m_data = new char[len+1];
		strcpy(m_data, str);
	}
}
String::String(const String& rhs) {
	if(rhs.m_data == NULL) {
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		int len = static_cast<int> (strlen(rhs.m_data));
		m_data = new char[len+1];
		strcpy(m_data, rhs.m_data);
	}
}
String& String::operator =(const String& rhs) {
	if(this == &rhs) return *this; // *别落下!*
	delete []m_data;  // *一定要先释放以前的!*
	if(rhs.m_data == NULL) {
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		int len = static_cast<int> (strlen(rhs.m_data));
		m_data = new char[len+1];
		strcpy(m_data, rhs.m_data);
	}
	return *this;
}
String::~String() {
	delete []m_data;
}
int main() {
	String s("hello");
	String s1("hi");
	s = s1;
	s.show();
	return 0;
}

posted @ 2013-04-12 12:27  小尼人00  阅读(347)  评论(0编辑  收藏  举报