[面试] 写出 string 类的构造,析构,复制构造函数,复制操作符!

#include <iostream> // 。。。
#define BUG puts("here!!!");

using namespace std;
class String {
private :
	char *m_data;
public :
	String(const char *str = NULL); // 构造函数
	String(const String &other);    // 拷贝构造函数
	~String();
	String& operator= (const String &other); // 赋值函数
};	
String::String(const char* str) {
	if(str == NULL) {
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		int len = static_cast<int> (strlen(str));
		m_data = new char[len + 1];
		strcpy(m_data, str);
	}
}
String::String(const String &other) {
	if(other.m_data == NULL) {
		m_data = new char[1];
		*m_data = '\0';
	}
	else {
		int len = strlen(m_data);
		m_data = new char[len+1];
		strcpy(m_data, other.m_data);
	}
}
String& String::operator= (const String& other) {
	if(this == &other) return *this;
	delete []m_data;
	if(other.m_data == NULL) {
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		int len = strlen(other.m_data);
		m_data = new char[len+1];
		strcpy(m_data, other.m_data);
	}
	return *this;
}
String::~String() {
	delete []m_data;
}
int main() {
	String sa, sb;
	sa = "abcde";
	String sc(sa);
	return 0;
}

posted @ 2013-03-10 20:59  小尼人00  阅读(164)  评论(0编辑  收藏  举报