#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);
cout << "Person(int age, int height)" << endl;
}
Person(const Person& p)
{
cout << "Person(const Person& p)" << endl;
m_age = p.m_age;
//this->m_height = p.m_height;
this->m_height = new int(*p.m_height);
}
~Person()
{
m_age = 0;
if (m_height)
{
delete m_height;
m_height = NULL;
}
delete m_height;
cout << "~Person()" << endl;
}
int m_age;
int* m_height;
};
int main()
{
Person p1(20,180);
Person p2 (p1);
cout <<"age:" << p1.m_age << " " << "height:"<< * p1.m_height << endl;
cout <<"age:" << p2.m_age << " " << "height:"<< *p2.m_height << endl;
return 0;
}
同一块空间不能连续释放两次。
现代写法则需要通过swap()来实现。
通过string来展示。