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!\n");
C c;
A* pA = &c;
B* pB = &c;
pA->foo(); //這里會輸出和A相關的信息
pB->foo(); //這里會輸出和B相關的信息
return 0;
}
