一.代码
#include <iostream>
using namespace std;
class person {
public:
person() {
}
person(int age,int hight) {
cout << "有参构造" << endl;
m_age = age;
m_hight = new int(hight);
}
person(const person& p) {
cout << "拷贝构造" << endl;
m_age = p.m_age;
m_hight = new int(*p.m_hight);
}
~person() {
cout << "析构函数" << endl;
if (m_hight != NULL) {
delete m_hight;
m_hight = NULL;
}
}
int m_age;
int* m_hight;
};
void test01() {
person p1(18,160);
cout << "p1的年龄为:" << p1.m_age << "p1的身高为: " << *p1.m_hight << endl;
person p2(p1);
cout << "p2的年龄为:" << p2.m_age << "p2的身高为: " << *p2.m_hight << endl;
}
int main() {
test01();
return 0;
}
二.解析
拷贝构造函数,是一种特殊的构造函数,它在创建对象时,是使用同一类中之前创建的对象来初始化新创建的对象。