直接贴代码吧,这段时间准备面试也正好练习了一下。
class String{public: String(const char *str = ""); ~String(void); String(const String &other); String &operator =(const String &other); size_t size(void) const; const char *c_str(void); private: char *m_str;};String::String(const char *str){ int len = strlen(str); m_str = new char[len + 1]; strcpy(m_str, str);}String::~String(void){ delete []m_str;}String::String(const String &other){ int len = strlen(other.m_str); m_str = new char[len + 1]; strcpy(m_str, other.m_str);}String& String::operator=(const String &other){ if (other == *this) return *this; delete []m_str; int len = strlen(other.m_str); m_str = new char[len + 1]; strcpy(m_str, other.m_str); return *this;}size_t String::size(void){ return strlen(m_str);}const char* String::c_str(void){ return m_str;}