前几天我的一个同学在IBM笔试中遇到一道C++题,大概意思就是:
#include <stdio.h>
class Base {
virtual void f(int i){printf("Base");}
};
class Derive { //补充!注意,这里没有继承Base
public:
virtual void f(int i){printf("Derive");}
};
int main(int,char**)
{
Derive* pd = (Derive*)new Base;
pd->f(1);
return 0;
}
What is the output?
要是将Base中的f(int i)改成 anything(int i)就更有难度了。
#include <stdio.h>
class Base {
virtual void func(int i) { printf("base!!!
"); }
virtual void f(int i) { printf("base..."); }
};
class Derive {
public:
virtual void f(int i) { printf("derive..."); }
virtual void func1(int i) { printf("derive!!!
"); }
};
int main() {
Base b, *pb;
Derive d, *pd;
pd = (Derive *)new Base;
pd->func1(1);
return 0;
}
输出:Base…
编译器只是取出对象的vftable然后找到虚函数表首地址,然后“偏移”,然后调用。
根本不管调用函数的名字、参数列表和访问权限。如果恰巧参数列表中的参数在栈中的大小一样,那就成功调用了,如果不一样,就会出现运行时错误(检查堆栈时报错)