Class inherited from class without default constructor

别说谁变了你拦得住时间么 提交于 2019-11-27 06:15:00

问题


Right now I have a class A that inherits from class B, and B does not have a default constructor. I am trying the create a constructor for A that has the exact same parameters for B's constructor, but I get:

error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)

How would I fix this error?


回答1:


The constructor should look like this:

A(int i) : B(i) {}

The bit after the colon means, "initialize the B base class sub object of this object using its int constructor, with the value i".

I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-existent no-args constructor.




回答2:


You need to invoke the base constructor via your class' initializer list.

Example:

class C : public B
{
public:
    C(int x) : B(x)
    {
    }

};

When you don't initialize B explicitly it will try to use the default constructor which has no parameters.



来源:https://stackoverflow.com/questions/3714162/class-inherited-from-class-without-default-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!