当类的成员变量为字符串的时候,注意深拷贝
#include#include #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; }
本文标题:当类的成员变量为字符串的时候,注意深拷贝
URL链接:http://scjbc.cn/article/gjdjid.html