如下是拷贝构造函数的几种情况:可以仔细分析一下
#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;
}
这样就可以了