#include <iostream> #include <cstring> #strcpy using namespace std; class String{ public: String(const char* str = NULL): m_str(strcpy(new char[strlen(str?str:"")+1], str?str:"")){} ~String(){ if(m_str){ delete [] m_str; m_str = NULL; } } //拷贝构造 String(const String& that): m_str(strcpy(new char[strlen(that.m_str)+1],that.m_str)){} //拷贝赋值,成员变量m_str为指针为指针时,要注意深拷贝,这里为深拷贝 String& operator=(const String& that){ if(&that != this){ char* = new char[strlen(that.m_str)+1]; delete[] m_str;//先释放旧资源 m_str = strcpy(str,that.m_str); } return *this; } friend ostream& operator<<(ostream& os,const String&c){ os << c.m_str; return os; } //c接口 const char* c_str(void)const{ return m_str; } public: char* m_str; }; int main(void){ String s1("hello,world"); cout << s1 << endl; return 0; }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。