include
using namespace std;
//深拷贝与浅拷贝
class person {
public:
person() {//无参构造函数(默认构造函数)
cout << “person的无参构造函数调用” << endl;
}
person(int a, int b) {//有参构造函数
age = a;
height = new int(b);
cout << “person的有参构造函数调用” << endl;
}
//拷贝构造函数参数必须为引用 是为了防止调用拷贝构造函数陷入死循环。
person(const person& a) {//拷贝构造函数
age = a.age;
//height = a.height;//编译器默认实现的浅拷贝操作
height = new int(a.height);//深拷贝操作
cout << “person的拷贝构造函数调用” << endl;
}
~person() {
if (height != NULL) {
delete height;
height = NULL;
}
cout<< “person的析构函数调用” << endl;
}
int age;
int
height;
};
void test() {
//person p1;//默认构造函数
person p2(10,160);//有参构造函数
person p3(p2);//拷贝构造函数
//cout <<”年龄为:” < cout << “年龄为:” << p2.age << “身高为:” << p2.height << endl;
cout << “年龄为:” << p3.age << “身高为:” <<
p3.height << endl;
}
int main() {
test();
return 0;
}