gpt4 book ai didi

C++ - 在另一个类中实例化对象时调用默认构造函数以外的构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:59 24 4
gpt4 key购买 nike

随意编辑标题,我不确定如何表达。

我正在尝试弄清楚在另一个类中实例化时如何调用类的默认构造函数而不是默认构造函数。我的意思是这个……

class A
{
public:
A(){cout << "i get this default constructor when I create a B" << endl;}
A(int i){cout << "this is the constructor i want when I create a B" << endl;}
};

class B
{
A a;
};

int main()
{
B *ptr = new B;
return 0;
}

我已经进行了一些搜索,但没有找到一种方法来做我想做的事。我想也许在 B 的声明中我可以做 A a(5) 但这不起作用。

谢谢

最佳答案

您可以使用 constructor initialization list 来做到这一点(您可能还想查看 this question 和其他类似的内容)。

这意味着您必须手动为 B 编写构造函数:

class B
{
A a;

public: B() : a(5) {}
};

See it in action .

关于C++ - 在另一个类中实例化对象时调用默认构造函数以外的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206895/

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