我有一个'D'类,它有一个成员函数'play'。 Play应该采用两个参数,即“A”类的对象。我还有另外两个类,'B'和'C',它们都是从'A'类继承(保护)的。我的程序结构的方式,我只有一个'B'对象和另一个'C'传递给'play'功能。我怎样才能做到这一点?如果我传递这两个继承的对象,我会收到编译器错误:
cannot cast 'B' to its protected base class 'A'
我是否需要将对象强制转换回'A'对象才能将它们传递给'play'?或者我可以以某种方式使用它们吗?
答案 0 :(得分:2)
您可以通过引用传递class B
和class C
的对象。
例如:void play(A* b,A* c);
由于B
和C
是A
的子项,A
的指针可以保存该对象。但是您需要声明B
和C
中要在Class D
Class A
内{{1}}使用的所有功能。
答案 1 :(得分:1)
如果我已正确解释您的代码,您的情况为the following:
struct A {};
struct B : protected A {};
struct C : protected A {};
struct D {
void play(A a, A b) {}
};
然后你应该公开继承并接受play
成员函数中的 const引用(或引用),如this:
struct A {};
struct B : public A {};
struct C : public A {};
struct D {
void play(A const& a, A const& b) {}
};