using namespace std;
// 深拷贝,浅拷贝
class Person { public: Person() { cout << “Person 的默认构造函数” << endl; }
Person(int val, int height) {m_Height = new int(height);age = val;cout << "Person 的有参构造函数" << endl;}// 自己实现拷贝构造函数, 解决浅拷贝带来的问题Person(const Person& p) {cout << "Person 拷贝构造函数的调用" << endl;age = p.age;//m_Height = p.m_Height; // 编译器默认实现就是这行代码m_Height = new int(*p.m_Height);}~Person() {// 析构代码,将堆区开辟的数据做释放操作if (m_Height != NULL) {delete m_Height;m_Height = NULL;}cout << "Person 的析构函数" << endl;}int age;int* m_Height; //身高
};
void test01() { Person p1(18, 160);
cout << "p1的年龄为: " << p1.age << endl;cout << "p1的身高为: " << *p1.m_Height << endl;Person p2(p1);cout << "p2的年龄为: " << p2.age << endl;cout << "p2的身高为: " << *p2.m_Height << endl;
} int main() { test01(); system(“pause”); return 0; } ```
总结:如果有属性是在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题
