覆盖多重继承中的函数的语法

时间:2013-11-04 08:45:03

标签: c++ multiple-inheritance

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()
};

没有任何虚拟或覆盖?我不明白可访问性。谢谢。

1 个答案:

答案 0 :(得分:4)

Leonard Lie,

要覆盖你可以简单地声明具有相同名称的函数,以实现代码中注释的功能,你需要将一个变量传递给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个可能的版本,但您可以使用enumint来适应具有更多选项的情况。< / p>