作者:jicanmeng
时间:2014年12月04日
多继承就是一个派生类同时继承了两个基类的属性和方法。
看一个例子:
#include <iostream> using namespace std; class USBDevice { private: long m_lID; public: USBDevice(long lID) : m_lID(lID) { cout << "USBDevice constructor" << endl; } long GetID() { return m_lID; } }; class NetworkDevice { private: long m_lID; public: NetworkDevice(long lID) : m_lID(lID) { cout << "NetworkDevice constructor" << endl; } long GetID() { return m_lID; } }; class WirelessAdaptor: public USBDevice, public NetworkDevice { public: WirelessAdaptor(long lUSBID, long lNetworkID) : NetworkDevice(lNetworkID), USBDevice(lUSBID) { cout << "WirelessAdaptor constructor" << endl; } }; int main() { WirelessAdaptor c54G(5442, 181742); // cout << c54G.GetID(); // Which GetID() do we call? cout << c54G.USBDevice::GetID(); cout << c54G.NetworkDevice::GetID(); return 0; }
以下是运行结果:
[jicanmeng@andy tmp]$ ./a.out
USBDevice constructor
NetworkDevice constructor
WirelessAdaptor constructor
[jicanmeng@andy tmp]$
对于这个例子,需要注意两点:
多继承使用起来容易出错。learncpp.com上面建议大家使用的时候要非常小心。其它语言对多继承的使用或多或少有一些限制。(Many object-oriented languages (eg. Smalltalk, PHP) do not even support multiple inheritance. Many relatively modern languages such as Java and C# restricts classes to single inheritance of normal classes, but allow multiple inheritance of interface classes (which we will talk about later). )