继承中的二义性归属问题
2015-08-13 15:28
411 查看
当一个基类产生多个子类,这些子类又产生新的子类时,调用基类的成员函数会产生二义性问题
代码示例
结果演示
定义为虚基类可解决二义性问题,不必再添加成员限定符
代码演示
结果演示
或者是每个类都定义自己的成员函数,函数名可以相同,编译时自动调用
代码示例
结果演示
代码示例
/* human / \ mother father \ / son */ #include <iostream> using namespace std; class human { public: void stand(){ cout << "hehe" << endl; } }; class mother :public human { }; class father :public human { }; class son :public father, public mother { }; int main() { son tom; //tom.stand()//会有二义性,编译器不知道stand()函数是指从mother继承来的还是从father继承来的 tom.mother::stand();//指明stand()函数是从mother那里继承来的,用::标识符(成员限定符) return 0; }
结果演示
定义为虚基类可解决二义性问题,不必再添加成员限定符
代码演示
#include <iostream> using namespace std; class human { public: void stand(){ cout << "人类能够直立行走" << endl; } }; class mother :virtual public human //virtual的意思是虚的,也就是定义虚基类 { }; class father :virtual public human //每个子类都定义虚基类 { }; class son :public father, public mother { public: }; int main() { father mike; mike.stand(); mother jane; jane.stand(); human man; man.stand(); son tom; tom.stand(); return 0; }
结果演示
或者是每个类都定义自己的成员函数,函数名可以相同,编译时自动调用
代码示例
#include <iostream> using namespace std; class human { public: void stand(){cout<<"人类能够直立行走"<<endl;} }; class mother:virtual public human { public: void stand(){cout<<"母类能够直立行走"<<endl;} }; class father:virtual public human { public: void stand(){cout<<"父类能够直立行走"<<endl;} }; class son:public father,public mother { public: void stand(){cout<<"子类能够直立行走"<<endl;} }; int main() { son tom; tom.stand(); father mike; mike.stand(); mother jane; jane.stand(); human man; man.stand(); return 0; }
结果演示
相关文章推荐
- [转载] Hadoop和Hive单机环境搭建
- 使用观察者模式处理异常信息
- java设计模式之---工厂模式
- SpringMvc的xml文件的配置
- EasyUI datagrid数据表格--获取datagrid中选中行的数据
- 剖析XX联盟 - 英雄对象类
- SpringMVC启动一直卡的解决
- 使用 iscroll 实现焦点图无限循环
- jQuery插件手把手教会(一)
- eclipse 快捷键大全,eclipse查找类,文件,添加注释
- Android开发必知--几种不同对话框的实现
- ChartControl饼状图自定义调色板
- solr添加IK分词和自己定义词库
- Cat VS Dog---hdu3829(最大独立集)
- Vs2010 调试快捷键
- js实现类似微信网页版在可编辑的div中粘贴内容时过滤剪贴板的内容,光标始终在粘贴内容后面,以及将光标定位到最后的方法
- Highmaps网页图表教程之Highmaps第一个实例与图表构成
- oracle 登录
- css学习笔记之三
- Linux