C++中沒有super或parent關鍵字,想要調父類方法,只能使用明確的[父類名稱::方法名]ios
假如要求A和B是C的父類的前提下,要使以下代碼可以分別輸出A和B的相關信息(雖然這個要求不多遇到....,可是面試官就是這麼變態)面試
int main(int argc, char* argv[]) { C c; A* pA = &c; B* pB = &c; pA->foo(); //這裏會輸出和A相關的信息 pB->foo(); //這裏會輸出和B相關的信息 return 0; }
怎麼辦?app
// test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; class A { public: virtual void foo() {cout<<"A::foo()"<<endl;} protected: private: }; class B { public: virtual void foo() {cout<<"B::foo()"<<endl;} protected: private: }; class MidA:public A { public: virtual void fooCA() {}; virtual void foo() { A::foo(); } protected: private: }; class MidB:public B { public: virtual void fooCB() {}; virtual void foo() { B::foo(); } protected: private: }; class C:public MidA, public MidB { }; int main(int argc, char* argv[]) { printf("Hello World!\n"); C c; A* pA = &c; B* pB = &c; pA->foo(); //這裏會輸出和A相關的信息 pB->foo(); //這裏會輸出和B相關的信息 return 0; }