首页 > 代码库 > 多重继承的注意点
多重继承的注意点
1, 钻石型多重继承如果不想要底部的类有重复的变量,则需要声明为virtual继承
class File{...};
class InputFile: virtual public File{..};
class OutputFile: virtual public File{....};
class IOFile: public InputFile,
public OutputFile
{...};
2, 多重继承来的成员函数指向一边的指针不能访问另一边的函数
/////////////////////////////////////////////////////////////////////////////////// FileName : multi_inherit.h// Version : 0.10 created 2013/11/08 00:00:00 // Author : Jimmy Han// Comment : /////////////////////////////////////////////////////////////////////////////////#ifndef MULTI_INHERIT_H#define MULTI_INHERIT_Hclass base1{public: void baseFunc();private: int baseElem;};class derive1 : public base1 {public: void derive1Func();private: int derive1Elem;};class base2{public: void baseFunc();private: int baseElem;};class derive2 : public derive1, public base2{public: void derive2Func(); //to avoid ambigous void baseFunc(); private: int derive2Elem;};#endif
/////////////////////////////////////////////////////////////////////////////////// FileName : multi_inherit.cpp// Version : 0.10// Author : Ryan Han// Date : 2013/07/26 16:50:14// Comment : /////////////////////////////////////////////////////////////////////////////////#include "multi_inherit.h"#include <iostream>using namespace std;void base1::baseFunc() { cout << "base1Func was called. " << endl;}void base2::baseFunc() { cout << "base2Func was called. " << endl;}void derive1::derive1Func() { cout << "derive1Func was called. " << endl;}void derive2::derive2Func() { cout << "derive2Func was called. " << endl;}void derive2::baseFunc() { base2::baseFunc();}
/////////////////////////////////////////////////////////////////////////////////// FileName : multi_inherit_client.cpp// Version : 0.10// Author : Ryan Han// Date : 2013/07/26 16:50:14// Comment : // Output :// $ ./a// $ ./a.exe// base2Func was called.// derive1Func was called.// derive2Func was called.// base1Func was called.// derive1Func was called.///////////////////////////////////////////////////////////////////////////////#include "multi_inherit.h"#include <iostream>using namespace std;int main() { derive2 d2; //if not embed, this will be ambigous and compile error d2.baseFunc(); //could call both derive1Func and derive2Func d2.derive1Func(); d2.derive2Func(); derive1* b1 = new derive2; //call base1 or derive1 functions, OK b1->baseFunc(); b1->derive1Func(); //call base2 or derive2 functions, compile error. //b1->derive2Func(); return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。