什么是菱形继承带来的二义性问题

来源:互联网 发布:睡了学生妈妈 知乎 编辑:程序博客网 时间:2024/04/25 16:35

首先来看一下这段代码:

#include<iostream>using namespace std;class Grandam{public:    void introduce_self()    {        cout << "I am grandam." << endl;    }};class Mother :public Grandam{public:    void introduce_self()    {        cout << "I am mother." << endl;    }};class Aunt :public Grandam{public:    void introduce_self()    {        cout << "I am aunt." << endl;    }};class Daughter :public Mother,public Aunt{public:    void introduce_self()    {        cout << "I am daughter." << endl;    }};int main(){    Grandam* ptr;    Daughter d;    ptr = &d;    ptr->introduce_self();    return 0;}

对该程序进行编译,出现如图问题:
这里写图片描述
这就是二义性问题,Mother和Aunt都继承了Grandam,而Daughter多继承了Mother和Aunt,这样在调用对象d时,编译器不知道要调用来自Mother里的成员函数introduce_self(),还是来自Aunt里的introduce_self(),所以编译时会出错。

二义性的解决方法过程详细分析,见下篇文章:
http://blog.csdn.net/lxp_mujinhuakai/article/details/69427582

0 0