13.22 假定我们希望HasPtr的行为像一个值。即,对于对象所指向的string成员,每个对象都有一份自己的拷贝。
#include<iostream> #include<string> #include<new> using namespace std; class HasPtr { public: HasPtr(const string &s=string()):ps(new string(s)),i(0){cout<<"constructer"<<endl;} HasPtr(const HasPtr &h):i(h.i) { cout<<"copy constructer"<<endl; ps=new string; *ps=*h.ps;//只拷贝值 } HasPtr& operator=(const HasPtr &h) { auto newp=new string(*h.ps); delete ps; ps=newp; i=h.i; return *this; } ~HasPtr() { delete ps; cout<<"destructer"<<endl;} private: string *ps; int i; }; int main() { HasPtr h; HasPtr hh(h); hh=h; return 0; }
时间: 2024-09-28 12:44:05