简体   繁体   English

多继承中重写函数的语法

[英]syntax for overriding function in 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()}
};

how do you override the func1? 如何覆盖func1? or can you just define it 或者你可以定义它

class Derived: public A, public B
{
    public:

    void func1()
};

without any virtual or override? 没有任何虚拟或替代? I don't understand the accessibility. 我不了解可访问性。 Thank you. 谢谢。

Leonard Lie, 伦纳德·李

to override you can simply declare the function with the same name, to achieve the functionality in the comments in the code you need a variable being passed to Derived func1() 要覆盖,您可以简单地使用相同的名称声明函数,要在代码的注释中实现功能,您需要将变量传递给Derived func1()

For example: 例如:

#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;
}

This should do what you are looking for, I have used a boolean as there are only 2 possible versions, but you could use an enum or int to suit a case with more options. 这应该可以满足您的需求,我使用了布尔值,因为只有两个可能的版本,但是您可以使用enumint来适应具有更多选项的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM