loo*_*oop 1 c++ constructor 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;
}
Run Code Online (Sandbox Code Playgroud)
我做了一些搜索,但我没有办法做我想做的事.我想也许在B的声明中我可以这样做,A a(5)
但那不起作用.
谢谢
Jon*_*Jon 10
您可以使用构造函数初始化列表执行此操作(您可能还需要查看此问题以及与此类似的其他问题).
这意味着您必须手动编写构造函数B
:
class B
{
A a;
public: B() : a(5) {}
};
Run Code Online (Sandbox Code Playgroud)