我有以下代码,我不明白,为什么在创建对象 b 时,没有调用类 A 的构造函数.......我将不胜感激。非常感谢。
#include <iostream>
using namespace std;
class MyClass
{
int x;
public:
MyClass(int y);
MyClass(MyClass &my)
{
x = my.x;
cout << "My class created by copy" << endl;
}
};
MyClass::MyClass(int y)
{
x = y;
cout << "My class created" << endl;
}
class A {
MyClass k;
public:
A(MyClass &my) : k(my) {
cout << "A created" << endl;
}
};
class B {
A data;
public:
B(A& aa) : data(aa)
{
cout << "B created" << endl;
}
};
int main()
{
MyClass obj(100);
A a(obj);
B b(a);
return 0;
}
执行:
My class created
My class created by copy
A created
My Class created by copy
B created