关于多重继承和歧义 [英] About multiple inheritance and ambiguity

查看:307
本文介绍了关于多重继承和歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中:

  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(); //没有问题

GS a;
ah(); //错误

}



ah(); 给出歧义错误 q-> h(); p>

不会 * q GS 的实例

您使用多重继承会导致 A

code>出现在 GS 中。当您使用 S1 * q 访问 GS 实例时,它位于 A S1 相关联的实例。由于 S1 不实现 h(),输出 q-> h )将由 A 本身提供的实现。



c $ c> q-> h()使用由 S2 提供的实现,那么您需要使用虚拟继承创建一个菱形。这样做也将消除使用 ah()时的模糊性,因为虚拟继承将只导致一个 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 }
};


In the following example:

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

}

Why does a.h(); give an ambiguity error yet q->h(); doesn't?

Doesn't *q have an instance of GS which should cause the same ambiguity problem?

解决方案

Your use of multiple inheritance causes two instances of A to appear in GS. When you use S1 *q to access the GS instance, it follows the A instance associated with S1. Since S1 does not implement h(), the output of q->h() will be the implementation provided by A itself.

If you want q->h() to use the implementation provided by S2, then you need to create a diamond using virtual inheritance. Doing so will also remove the ambiguity when using a.h(), since virtual inheritance will cause only one instance of A to appear in 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; }
};

这篇关于关于多重继承和歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆