gpt4 book ai didi

C++类组合,为什么不调用构造函数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:01 25 4
gpt4 key购买 nike

<分区>

我有以下代码,我不明白,为什么在创建对象 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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com