0
点赞
收藏
分享

微信扫一扫

C++基础知识 - 多重继承的二义性问题

闲云困兽 2022-02-18 阅读 69

什么是二义性?

  • 简单来说就是一个班级有两个同名的人都叫张三, 老师叫张三回答这道题, 这时, 谁都不知道老师指的是哪个张三, 这就是二义
  • 多重继承的二义性就是在继承时,基类之间、或基类与派生类之间发生成员同名时,将出现对成员访问的不确定性——同名二义性
  • 当派生类从多个基类派生,而这些基类又从同一个基类派生,则在访问此共同基类中的成员时,将产生另一种不确定性——路径二义性。

demo

#include <iostream>
#include <Windows.h>

using namespace std;

class Father {
public:
	Father() {}
	~Father() {}
	void play() {cout << "Father KTV唱歌!" << endl;}
};

class Mother {
public:
	Mother() {}
	~Mother() {}
	void play() {cout << "Mother 逛街购物!" << endl;}
};

class Son : public Father, public Mother{
public:
	Son() {}
	~Son() {} 
};

int main(void) {
	Son son;
	
	son.play(); //无法确定该调用Fther的play()还是Mother的play()
	
	system("pause");
	return 0;
}

 

解决多重继承的二义性的方法1:

使用 “类名::” 进行指定, 指定调用从哪个基类继承的方法!

    son.Father::play();
	son.Mother::play();

 

解决多重继承的二义性的方法2:

在子类中重新实现这个同名方法, 并在这个方法内部, 使用基类名进行限定,
来调用对应的基类方法

class Son : public Father, public Mother{
public:
	Son() {}
	~Son() {} 
	void play() { 
		Father::play(); 
		Mother::play(); 
	}
};

int main(void) {
	Son son;
	son.play();		//调用自己类内部重写的play()方法
	
	system("pause");
	return 0;
}
举报

相关推荐

0 条评论