从多个基础覆盖虚函数 类

overriding virtual function from several base classes

假设我有这样的代码:

struct Base1 {
    virtual void foo() = 0;
};

struct Base2 {
    virtual void foo() = 0;
};

struct Derived : Base1, Base2 {
    void foo() override {}
};

我正在尝试为具有相同 name/signature.

的不同基础 类 的多个函数生成单个覆盖

在 c++ 中这样的压倒一切合法且定义明确吗?

Is such an overriding legal and well-defined in c++?

是的,只要你重写派生的虚函数就完全合法且定义明确class。
如果您创建一个 Derived 结构的对象并调用 foo 函数,它将调用被覆盖的函数。

编译器总是会从局部到全局范围搜索被​​调用的函数。因此,这里编译器将检查 foo 是否在 Derived 范围内定义,如果未找到,它将检查 Base 范围,并且由于您在派生范围内提供了 foo 的定义,编译器将不会检查基地范围。

试试这个代码,你会得到一个更好的主意。 输出将是This is derived.

#include <iostream>
using namespace std;
struct Base1 {
    virtual void foo() {
        cout << "This is base1" << endl;
    }
};

struct Base2 {
    virtual void foo() {
        cout << "This is base2" << endl;
    }
};

struct Derived : Base1, Base2 {
    void foo() {
        cout << "This is derived" << endl;
    }
};

int main() {
    Derived d;
    d.foo();
    return 0;
}