#include <iostream> #include <assert.h> using namespace std; //林锐P72 class String { public: String(const char *str = NULL); //普通构造函数 String(const String &other); // 拷贝构造函数 ~String(void); // 析构函数 String& operator =(const String &other); // 赋值函数 private: char *m_data; }; String::String(const char *str) { if (str == NULL) { m_data = new char[1]; *m_data = '/0'; // 按此规则,能够保证拷贝构造函数和赋值函数不需other.str == NULL 的判断.也可以使用m_data = NULL; } else { m_data = new char[strlen(str)+1]; assert(m_data != NULL); strcpy(m_data, str); } } String::~String() { delete [] m_data; // 就算m_data == NULL, 也是可以使用delete的. } // strlen() 函数不允许对NULL求长. String::String(const String &other) // 记住: 对于传引用,不需判断为空. 因为进来的时候肯定是个变量,而非指针. { m_data = new char[strlen(other.m_data)+1]; assert(m_data != NULL); strcpy(m_data, other.m_data); } String& String::operator=(const String &other) { if (this == &other) // 防止自赋值, 注意不要写为 *this == other, 这样的话,需要重载 "==" 运算符才行的. return *this; delete [] m_data; m_data = new char[strlen(other.m_data)+1]; assert(m_data != NULL); strcpy(m_data, other.m_data); return *this; } int main() { String s("hello"); String a("world"); s = a; return 0; }