繁体   English   中英

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

[英]C++ - Calling a constructor other than the default when an object is instantiated in another class

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

我试图弄清楚如何在另一个类中实例化除默认值之外的其他类的构造函数。 我的意思是

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)但这不起作用。

谢谢

您可以使用构造函数初始化列表来做到这一点(您可能还想看看这个问题和其他类似问题 )。

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

class B
{
    A a;

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

看到它在行动

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM