伦纳德·莱
要覆盖,您可以简单地声明具有相同名称的函数,以实现代码中注释中的功能,您需要将变量传递给 Derived func1()
例如:
#include <iostream>
using namespace std;
class A
{
protected:
void func1() { cout << "class A\n"; } //DO I need to call this virtual?
};
class B
{
protected:
void func1() { cout << "class B\n"; } //and this one as well?
};
class Derived: public A, public B
{
public:
//here define func1 where in the code there is
//if(statement) {B::func1()} else {A::func1()}
void func1(bool select = true)
{
if (select == true)
{
A::func1();
}
else
{
B::func1();
}
}
};
int main()
{
Derived d;
d.func1(); //returns default value based on select being true
d.func1(true); //returns value based on select being set to true
d.func1(false); // returns value base on select being set to false
cout << "Hello World" << endl;
return 0;
}
这应该可以满足您的需求,我使用了布尔值,因为只有 2 个可能的版本,但是您可以使用enum
orint
来适应具有更多选项的情况。