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

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

4

1 回答 1

4

伦纳德·莱

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

于 2013-11-04T08:54:18.347 回答