您的位置:首页 > 编程语言 > C语言/C++

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

2014-01-10 10:54 471 查看

多重继承(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


本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387944
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: