#include<iostream>
using namespace std;
class person {
public:
int age;
int* p;
person(int age) :age(age),p(new int(3)) { cout << "构造函数" << endl; }
person(person& per)
{
age = per.age;
#if 0
p = per.p;
#else
p = new int;
*p = *per.p;
#endif
cout << "拷贝构造函数" << endl;
}
~person()
{
delete(p);
p = nullptr;
cout << "析构函数" << endl;
}
void show()
{
cout << "age:" << age << " p:" << p << " *p:" << *p << endl;
}
person& operator=(const person& per)
{
age = per.age;
p = new int(1);
return *this;
}
};
int main()
{
#if 0
person p1(10), p2(p1);
//p2.show();
//p2.p = new int(20);
p1.show();
p2.show();
//p2.p = new int(20);
#else
person p1(1), p2(2);
p2 = p1;
p1.show();
p2.show();
#endif
return 0;
}
默认赋值运算是浅拷贝,默认拷贝构造函数也一样