问题
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