#include <string>
#include <iostream>
#include <memory>
using namespace std;
class HasPtr{
public:
HasPtr(const string &s = string()):
ps(new string(s)),i(0){}
HasPtr(const HasPtr &);
void print()const
{
cout << "*ps is:" << *ps <<endl;
cout << "ps is:" << ps << endl;
cout << "i is:" << endl;
}
private:
string *ps;
int i;
};
//拷贝ps指向的对象,而不是拷贝指针ps本身
HasPtr::HasPtr(const HasPtr &h):i(h.i),ps(new string(*(h.ps))){}
int main()
{
HasPtr p1("you are good");
p1.print();
HasPtr p2(p1);
p2.print();
}
运行结果是:
*ps is:you are good
ps is:0x55fadaffeeb0
i is:
*ps is:you are good
ps is:0x55fadafff2f0
i is: