C++中没有super或parent关键字,想要调父类方法,只能使用明确的[父类名称::方法名]
假如要求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; }
怎么办?
// 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! "); C c; A* pA = &c; B* pB = &c; pA->foo(); //这里会输出和A相关的信息 pB->foo(); //这里会输出和B相关的信息 return 0; }