#include <iostream>
using namespace std;
class Computer
{
//方便访问private
friend void test();
public:
//普通构造函数
Computer(int price, int year)
// : m_price(price), year(p)
{
m_price = price;
m_year = new int(year);
}
//深拷贝构造函数
Computer(const Computer& comter)
{
m_price = comter.m_price;
//这样写会导致当前对像的指针地址与comter对象的指针地址重复
//导致析构产生重复释放同一内存报错
//this->m_p = comter.m_p;
//开辟新内存给新对象的指针变量
m_year = new int(*comter.m_year);
}
//堆区手动申请内存,也要手动释放
~Computer()
{
cout << "进行析构" << endl;
if (m_year != NULL)
{
delete this->m_year;
m_year = NULL;
}
}
private:
int m_price;
int* m_year;
};
void test()
{
//调用普通构造函数
Computer comter1(200, 2000);
cout << "普通构造函数的price和指针p为: "
<< comter1.m_price
<< "\t"
<< *comter1.m_year
<< endl;
//深拷贝构造函数
Computer comter2(comter1);
cout << "深拷贝构造函数的price和指针p为: "
<< comter2.m_price
<< "\t"
<< *comter2.m_year
<< endl;
}
int main()
{
test();
system("pause");
return 0;
}
深拷贝构造函数
最新推荐文章于 2024-04-13 10:24:51 发布