#include <iostream> #include <string.h> /* String 类 */ class String{ char* str; public: String(); String(const char* s); String(String&s); ~String(); const char* getStr() const; String& operator = (const char* s); String& operator = (const String &s); friend std::ostream& operator <<(std::ostream& o, const String &s); }; /*无参构造*/ String::String():str(NULL){} /*参数字符串构造*/ String::String(const char* s){ str = new char[strlen(s) + 1]; strcpy(str,s); } /*拷贝构造*/ String::String(String &s){ str = new char[strlen(s.str) + 1]; strcpy(str,s.str); } /*析构*/ String::~String(){ if(str) delete str; } /*返回对象的数据成员str*/ const char* String::getStr() const{ return str; } /*重载 = 对象已经存在*/ String& String::operator =(const char*s){ if(str) delete str; str = new char[strlen(s) + 1]; strcpy(str,s); return *this; } /* 重载 = */ String& String::operator = (const String &s){ if(this!=&s){ if(str) delete str; str = new char[strlen(s.str) + 1]; strcpy(str,s.str); } return *this; } /* 友元函数重载 << */ std::ostream& operator <<(std::ostream& o, const String &s) { o << s.str << std::endl; return o; } int main() { return 0; }