c++ - 关于多重继承和歧义

标签 c++ c++11 multiple-inheritance ambiguity

在下面的例子中:

class A {
public:
    virtual void f() { cout << "a" << endl; }
    virtual void h() { cout << "A" << endl; }
};
class s1 : public A {
public:
    virtual void f() { cout << "s1" << endl; }
};
class s2 : public A {
public:
    virtual void h() { cout << "s2" << endl; }
};
class GS : public s1, public s2 {
public:
};
int main()
{
    s1 *q = new GS;
    q->h();//no problem

    GS a;
    a.h();//error

}

为什么 a.h(); 给出歧义错误而 q->h(); 却没有?

难道 *q 没有一个 GS 的实例会导致同样的歧义问题吗?

最佳答案

您对多重继承的使用导致 A 的两个实例出现在 GS 中。当您使用 S1 *q 访问 GS 实例时,它遵循与 S1 关联的 A 实例。由于 S1 没有实现 h()q->h() 的输出将是 A< 提供的实现 本身。

如果你想让q->h()使用S2提供的实现,那么你需要使用虚拟继承来创建一个钻石。这样做还会消除使用 a.h() 时的歧义,因为虚拟继承只会导致 A 的一个实例出现在 GS 中。

class s1 : virtual public A {
public:
    virtual void f() { cout << "s1" << endl; }
};
class s2 : virtual public A {
public:
    virtual void h() { cout << "s2" << endl; }
};

关于c++ - 关于多重继承和歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35095227/

相关文章:

c++ - WINAPI SQLite C 无法正确地将数据插入数据库

c++ - OpenGL:二维四边形应该如何存储/渲染?

c++ - 有哪些具有优秀编码风格的开源 C++ 项目?

c++ - 用专门的版本覆盖多个继承的模板函数

c++ - 为什么 int[] 被视为右值?

c++ - 如何根据空格删除字符串

c++ - 根据对象类型切换

c++ - 在成员函数返回的 vector 上调用开始和结束

c++ - 为什么 const/non-const 函数重载的继承不明确?

python - 使用多重继承,类没有来自父类的变量的属性