#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age, int height)
{
m_age = age;
m_height = new int(height);//回忆new的用法,其创建的height是个指针
cout << "Person的有参构造函数调用" << endl;
}
//解决方法:用深拷贝来代替浅拷贝
Person(const Person& p)
{
cout << "Person的拷贝构造函数调用" << endl;
m_age = p.m_age;
m_height = new int(*p.m_height);
}
~Person()
{
if (m_height != NULL)
{
delete m_height; //释放内存。这里我们人为释放内存,堆区本身是一个栈,符合先进后出的原则,p2拷贝p的属性,是后进的,要先出。这里就会先释放p2的m_height,
m_height = NULL; //因为p2浅拷贝的p的,p2的m_height也是p的m_height,p2的释放后,p的找不到了,就会报错。解决方法见上面
}
cout << "Person的析构函数调用" << endl;
}
int m_age;
int* m_height;
};
void test()
{
Person p(18, 160);
cout << "p的年龄为 " << p.m_age << "p的身高为 " << *p.m_height << endl;
Person p2(p);
cout << "p2的年龄为 " << p2.m_age << endl;
}
int main()
{
test();
system("pause");
return 0;
}
//不知道哪里出现了问题,运行时会报错访问权限冲突