C++拷贝构造函数源程序



如下是拷贝构造函数的几种情况:可以仔细分析一下


#include <iostream>
#include <string>
using namespace std;


class CStu
{
public:
CStu()
{
m_strName = "mengshuang";
cout << "01." << m_strName << endl;
}


CStu(const CStu& op)
{
m_strName = op.m_strName;
cout << "02." << m_strName << endl;
}
private:
string m_strName;
};


CStu fun(CStu op)
{
return op;
}


int main()
{
//CStu op; //调用01;
//CStu op2(op); //调用02;
//CStu op3 = op; //调用02;


CStu op4;
fun(op4); //调用01,02,02; 最后一个02是return的原因


//CStu op5 = CStu(op); //这个op5就不调用defalut constructors了


system("pause");
return 0;
}




浅拷贝&&深拷贝的区别


#include <iostream>
using namespace std;


class AA
{
public:
int *aa;
AA()
{
aa = new int[2];
aa[0] = 12; aa[1] = 13;
}


~AA()
{
delete [] aa;
}
};


int main()
{
AA op;
cout << op.aa[0] << op.aa[1] << endl;


AA op2 = op;
cout << op2.aa[0] << op2.aa[1] << endl;


system("pause");
return 0;
}


这样系统崩溃了,因为op2是浅拷贝,直接copy过来的,和op一样的地址,所以destructors对一个地址delete两次


深拷贝:
CStu(CStu& a)
{
//this -> a = a.a; //浅拷贝(系统默认的拷贝构造函数)
this ->a = new int[2];
this ->a[0] = 12;
this ->a[1] = 13;
}


这样就可以了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值