1.多重继承的问题(三)
多重继承可能产生多个虚函数表
eg:
#include <iostream> #include <string> using namespace std; class BaseA { public: virtual void funcA () { cout << "BaseA::funcA()" << endl; } }; class BaseB { public: virtual void funcB () { cout << "BaseB::funcB()" << endl; } }; class Derived : public BaseA, public BaseB { }; int main() { Derived d; BaseA* pa = &d; BaseB* pb = &d; // 指向同一对象的不同地方 BaseB* pbb = (BaseB*)pa; // 把pa指向到地址给到类pbb,此时pa指向到是BaseA cout << "sizeof(d) = " << sizeof(d) << endl; // 8 证明类中有两个指向虚函数表到指针。也就是 // 说 多重继承产生类多个虚函数表 // 这也是子类和父类叠加的结果 cout << "Using pa to call funcA()..." << endl; pa->funcA(); // 调用指针,指向虚函数表。在表中找到函数调用 cout << "Using pb to call funcB()..." << endl; pb->funcB(); cout << endl; cout << "Using pbb to call funcB()..." << endl; pbb->funcB(); // 此时pbb调用的是pa的虚函数表。此表中只有 // funcA()函数。所以无法实现要求 return 0; }
图解:
2.正确的使用多继承
单继承某个类 + 实现(多个)接口
eg:
#include <iostream> #include <string> using namespace std; class Base { protected: int mi; public: Base(int i) { mi = i; } int getI() { return mi; } }; class Interface1 { public: virtual void add(int i) = 0; virtual void minus(int i) = 0; }; class Interface2 { public: virtual void multiply(int i) = 0; virtual void divide(int i) = 0; }; class Derived : public Base, public Interface1, public Interface2 { public: Derived(int i) : Base(i) { } void add(int i) { mi += i; } void minus(int i) { mi -= i; } void multiply(int i) { mi *= i; } void divide(int i) { if( i != 0 ) { mi /= i; } } }; int main() { Derived d(100); return 0; }