C++从多个具有相同虚函数名的基类继承

标签 c++ function class virtual multiple-inheritance

我试过这段代码:

class A
{
    virtual void foo() = 0;
};

class B
{
    virtual void foo() = 0;
};

class C : public A, public B
{
    //virtual void A::foo(){}
    //virtual void B::foo(){}

    virtual void A::foo();
    virtual void B::foo();
};

void C::A::foo(){}
void C::B::foo(){}

int main()
{
    C c;
    return 0;
}

使用注释部分是可以的,但是当我尝试在类声明之外编写定义时,编译器会报错。 我正在使用 MSVC11 编译器,有人知道如何编写吗? 我需要将代码移动到 cpp 文件中。

谢谢~~

最佳答案

函数根据名称和参数类型覆盖基类的虚函数(见下文)。因此,你的类 C两个 虚函数 foo,一个继承自 AB。但是函数 void C::foo() 会覆盖 both:

[class.virtual]/2

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

正如我在评论中已经说过的,[dcl.meaning]/1 禁止在(成员)函数的声明中使用 qualified-id:

When the declarator-id is qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers [...]"

因此,任何 virtual void X::foo(); 作为 C 中的声明都是非法的。

代码

class C : public A, public B
{
    virtual void foo();
};

是 AFAIK 覆盖 foo 的唯一方法,它将覆盖 A::fooB::foo。除了引入另一层继承之外,没有办法对 A::fooB::foo 进行两种不同的覆盖:

#include <iostream>

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

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

struct CA : A
{
    virtual void foo() { std::cout << "A" << std::endl; }
};

struct CB : B
{
    virtual void foo() { std::cout << "B" << std::endl; }
};

struct C : CA, CB {};

int main() {
    C c;
    //c.foo();  // ambiguous

    A& a = c;
    a.foo();

    B& b = c;
    b.foo();
}

关于C++从多个具有相同虚函数名的基类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18398409/

相关文章:

c++ - 在 Windows 和 Linux 上构建 C++

c++ - C++ 中的点属性访问

c - 在终止程序之前存储值

performance - FillChar,但对于整数/基数

python - 多线程类(python)

c++ - 通过 StringSet 进行在线模式搜索

c++ - 将十进制 (SQL) 转换为 double C++

c++ - 为什么必须定义未使用的虚函数?

python - 从变量命名类?

java - 如何使单例类线程安全?