转载自: https://blog.csdn.net/shanghairuoxiao/article/details/77341126
之前看过了陈皓大神关于虚函数表的博客,感觉对多态和虚函数表理解又清楚了一些,但是前不久喷到一道网易的笔试题,主要考察的也是对虚函数的理解,当时在某些地方又纠结了一下,自己写一段代码来验证,加深理解。网易的原题和下面的代码可能不一样,记不太清了。根据自己的理解写了一段代码。
#include <iostream>
using namespace std;
class base
{
public:
void fun_no_virtual() { cout << "call fun_no_virtual in base" << endl; }
virtual void fun_virtual() { cout << "call fun_virtual in base" << endl; }
};
class derive : public base
{
public:
void fun_no_virtual() { cout << "call fun_no_virtual in derive" << endl; }
virtual void fun_virtual() { cout << "call fun_virtual in derive" << endl; }
};
int main()
{
base a;
derive b;
base *c;
derive* d;
c = &b;
c->fun_no_virtual();
c->fun_virtual();
c = (base*)&b;
c->fun_no_virtual();
c->fun_virtual();
d = (derive*)&a;
d->fun_no_virtual();
d->fun_virtual();
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
输出结果是:
call fun_no_virtual in base
call fun_virtual in derive
call fun_no_virtual in base
call fun_virtual in derive
call fun_no_virtual in derive
call fun_virtual in base
- 1
- 2
- 3
- 4
- 5
- 6
输出结果和我预料的一致,通过上面这段程序的运行结果充分说明了:
1 对于虚函数,通过对象去调用时,完全是查找虚函数表。无论被转化成派生类还是基类。
2 对于非虚函数,通过对象去调用,完全是根据对象类型去查找相应的函数指针,进行调用。