多继承同名隐藏举例
*/ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:text.cpp * 作者:常轩 * 微信公众号:Worldhello * 完成日期:2016年5月19日 * 版本号:V1.0 * 问题描述:多继承同名隐藏举例 * 程序输入:无 * 程序输出:见运行结果 */ //多继承同名举例1 通过作用域分辨符,明确地唯一标识了派生类中由基类所继承来的成员,达到了访问的目的,解决了成员被隐藏的问题 #include<iostream> using namespace std; class Base1{ public: int var; void fun() { cout<<"Member of Base1"<<endl; } }; class Base2{ public: int var; void fun() { cout<<"Member of Base2"<<endl; } }; class Derived:public Base1,public Base2{ public: int var; void fun() { cout<<"Member of Derived"<<endl; } }; int main() { Derived d; Derived* p=&d; d.var=1; d.fun(); d.Base1::var=2; d.Base1::fun(); p->Base2::var=3; p->Base2::fun(); return 0; }
运行结果:
//多继承同名举例2 #include<iostream> using namespace std; class Base0{ public: int var0; void fun0() { cout<<"Member of Base0"<<endl; } }; class Base1:public Base0{ public: int var1; }; class Base2:public Base0{ public: int var2; }; class Derived:public Base1,public Base2{ public: int var; void fun() { cout<<"Member of Derived"<<endl; } }; int main() { Derived d; d.Base1::var0=2; d.Base1::fun0(); d.Base2::var0=3; d.Base2::fun0(); return 0; }
运行结果: