编写类String的构造/析构函数,赋值操作符
class String { public: String(const char * str = NULL); //普通构造函数 String(const String &other); //复制构造函数 String & operator= (const String &other); //赋值操作符 ~String(); //析构函数 private: char *m_data; }; String::String(const char *str) { if (str == NULL) { m_data = new char[1]; m_data[1] = '\0'; } else { int lenght = strlen(str); m_data = new char[lenght + 1]; strcpy(m_data, str); } } String::String(const String &other) { int lenght = strlen(other.m_data); m_data = new char[lenght + 1]; strcpy(m_data, other.m_data); } String & String::operator= (const String &other) { if(&other == this) //证同测试 return *this; delete [] m_data; int lenght = strlen(other.m_data); m_data = new char[lenght + 1]; strcpy(m_data, other.m_data); return *this; //第一次写的时候忘记返回*this } String & String::operator= (const String &other) { String temp(other); // delete [] m_data; swap(m_data, other.m_data); return *this; //又忘记返回*this } String::~String() { delete [] m_data; }
网络上志同道合,我们一起学习网络安全,一起进步,QQ群:694839022