class A
{
protected:
void func1() //DO I need to call this virtual?
};
class B
{
protected:
void func1() //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()}
};
你如何覆盖 func1?或者你可以只定义它
class Derived: public A, public B
{
public:
void func1()
};
没有任何虚拟或覆盖?我不明白可访问性。谢谢。
Leonard Lie,
要重写,您可以简单地声明具有相同名称的函数,要实现代码注释中的功能,您需要将变量传递给 派生的func1()
例如:
#include <iostream>
using namespace std;
class A
{
protected:
void func1() { cout << "class An"; } //DO I need to call this virtual?
};
class B
{
protected:
void func1() { cout << "class Bn"; } //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
或 int
来适应具有更多选项的情况。