多重继承(multiple inheritance) 的 名称歧义(name ambiguity)


本文地址: http://blog.csdn.net/caroline_wendy/article/details/18077235


在多重继承中, 如果多个基类包含相同名字的成员函数, 则在派生类使用时, 容易发生歧义, 会导致出错;

解决方法是: 在派生类中重写基类方法, 覆盖原方法, 再指定基类范围(scope), 确定使用那个基类的方法, 可以避免歧义;


代码如下:

/*  * cppprimer.cpp  *  *  Created on: 2014.1.10  *      Author: Spike  */  /*eclipse cdt, gcc 4.8.1*/  #include <iostream> #include <string>  struct Base1 { 	void print (void) { 		std::cout << "Base 1" << std::endl;} };  struct Base2 { 	void print (void) { 		std::cout << "Base 2" << std::endl;} };  struct Derived1 : public Base1, public Base2 { 	void print (void) { //重写基类方法 		Base1::print(); //指定使用何种 		Base2::print(); 	} };  int main (void) { 	Derived1 d1; 	d1.print(); //名字相同时, 会发生命名冲突! } 

输出:

Base 1 Base 2