#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数的调用" << endl;
}
Person(int age, int height)
{
cout << "有参构造函数的调用" << endl;
m_age = age;
m_height = new int(height);
}
//自己创建拷贝函数,解决浅拷贝带来的问题
Person(const Person& p)
{
cout << "拷贝函数的调用" << endl;
m_age = p.m_age;
m_height = new int(*p.m_height);
//m_height = p.m_height;
}
~Person()
{
cout << "析构函数的调用" << endl;
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
}
int m_age;//年龄
int* m_height;//身高
};
void test01()
{
Person p(10,160);
cout << "p的年龄为" << p.m_age << " " << "p的身高为:" << *p.m_height << endl;
Person p2(p);
cout << "p2的年龄为" << p2.m_age << " " << "p2的身高为:" << *p2.m_height << endl;
Person p3(p2);
cout << "p3的年龄为" << p3.m_age << " " << "p3的身高为:" << *p3.m_height << endl;
}
int main()
{
test01();
return 0;
}
类和对象_对象特征_深拷贝和浅拷贝
最新推荐文章于 2024-07-08 21:23:20 发布