程序代码:
// Note:Your choice is C++ IDE
#include <iostream>
using namespace std;
class CA
{
public:
CA(int nX = 0)
{
m_nX = nX;
cout<<"CA(int nX = 0) "<<m_nX<<endl;
}
CA(const CA& r)
{
m_nX = r.m_nX;
cout<<"CA(const CA& r) "<<m_nX<<endl;
}
CA& operator == (const CA& r)
{
m_nX = r.m_nX;
cout<<"CA& operator == (const CA& r) "<<m_nX<<endl;
}
private:
int m_nX;
};
class CB
{
public:
CB(CA C1, CA C2) : m_CY(C1), m_CZ(C2)
{
//m_CY = C1;
//m_CZ = C2;
cout<<"CB(CA C1, CA C2) : m_CY(C1), m_CZ(C2)"<<endl;
}
CB(const CB& r)
{
m_CY = r.m_CY;
m_CZ = r.m_CZ;
cout<<"CB(const CB& r)"<<endl;
}
private:
CA m_CY;
CA m_CZ;
};
int main()
{
CA C1(1);
CA C2(2);
CB C3(C1, C2);
return 0;
}结果
CA(int nX = 0) 1
CA(int nX = 0) 2
CA(const CA& r) 2
CA(const CA& r) 1
CA(const CA& r) 1
CA(const CA& r) 2
CB(CA C1, CA C2) : m_CY(C1), m_CZ(C2)
1你人为地提供了拷贝构造函数,但函数体内没能写出正确的赋值行为,所以获取的成员值是随机数,也就是成员并没有初始化.
2当一个类CB包含类对象成员(CA),这里CB类的拷贝构造函数执行过程为先传参,传参的过程是从右到左,好像听同学讲汇编时说过参数压栈方式就是这样,然后完成初始化列表的内容.....
这是我的理解...