2

C++:继承的二义性

 3 years ago
source link: https://www.lpime.cn/article/110
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

继承二义性

继承的二义性

1.在继承时,基类之间、或基类与派生类之间发生成员同名时,将出现对成员访问的不确定性——同名二义性。

2.当派生类从多个基类派生,而这些基类又从同一个基类派生,则在访问此共同基类中的成员时,将产生另一种不确定性——路径二义性。

// 同名二义性
#include "iostream"
 
using namespace std;
 
class Parent_f
{
public:
    void show()
    {
        cout<<"This is Parent_f\n";
    }
};
class Parent_m
{
public:
    void show()
    {
        cout<<"This is Parent_m\n";
    }
};
class Son:public Parent_f,public Parent_m
{
public:
    void display()
    {
        cout<<"This is son\n";
    }
};
int main()
{
    Son son;
    son.show();
    son.display();
    cout << "Hello world!" << endl;
    return 0;
}

解决方式:

1.加限定符::,son.Parent_f::show();

2.在子类写一个同名,覆盖掉父类中的

菱形二义性

有最基类A,有A的派生类B、C,又有D同时继承B、C,那么若A中有成员a,那么在派生类B,C中就存在a,又D继承了B,C,那么D中便同时存在B继承A的a和C继承A的a,那么当D的实例调用a的时候就不知道该调用B的a还是C的a,就导致了二义性。

//"菱形问题"路径二义性

#include "iostream"
 
using namespace std;
 
class Grandpa
{
public:
    int year_old;
};
 
class Parent_f:public Grandpa {};
class Parent_m:public Grandpa {};
 
class Son:public Parent_f,public Parent_m {};
 
int main()
{
    Son son;
    son.year_old = 10;
    cout << "Hello world!" << endl;
    return 0;
}

1.在类中定义同名成员,覆盖掉父类中的相关成员。

2.使用作用域限定符,指明访问的是哪一个基类的成员。

3.虚继承、使用虚基类,将祖父类对象统一。

本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2021/04/28 13:49


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK