Using base default constructor (with parameters) for child class

旧街凉风 提交于 2019-12-25 01:48:17

问题


I have a class A which has to have a a class passed to it; From A I have two classes B and C; is it possible for B and C to use the constructor from A, as apposed to the default constructor.

     A
    / \
   B   C 

A::A(randomNumber &rnd)
{
    ....
}

回答1:


Yes, it is possible:

class B
{
public:
    B(randomNumber& rnd) : A(rnd) { }
    // ...
};

If you want to call A's constructor in B's default constructor, you will have to pass a global object: since A's construct accepts an lvalue reference, creating a temporary is not an option.

B() : A(global_random_number);



回答2:


Yes. Use

class B {
public:
   B() : A(someRndNum) {}
};

and same for C.




回答3:


You can use following syntax:

B::B() : A(aRandomNum)
{
    ....
}


来源:https://stackoverflow.com/questions/15569020/using-base-default-constructor-with-parameters-for-child-class

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