c++虚函数
- C/C++ code
#include <iostream>using namespace std;class animal{ int a;public: virtual void eat() { cout << "animal eat" << endl; } virtual void play() { cout << "animal play" << endl; }};class dog : public animal{ int b;public: void eat() { cout << "dog eat" << endl; } void play() { cout << "dog play" << endl; } virtual void run() { cout << "dog run"<< endl; }};int main(){ animal a1; dog d1; d1.eat(); return 0;}为什么在对象a1中只有一个animal类的vptr
而没有他自己的vptr,不是在dog类中定义了一个virtual void run();吗 不是应该有一个指向virtual void run();的虚表吗
用的是vc6.0
[解决办法]
vptr是指向虚函数表的指针,这个指针是animal类的成员变量,dog类继承于animal,也就继承了vptr。但是dog类的vptr与animal的vptr指向的不是同一个地址,也就是说子类与父类的虚函数表是不在一块的。
d1.__vfptr的值 和 &d1.__vfptr[0]的值是一样的,和d1.__vfptr[0]的值是不一样的
d1.__vfptr的值是虚表的首地址
d1.__vfptr[0]的值是虚表内第一个函数的地址
virtual void run()这个函数的地址是d1.__vfptr[2]的值哦
请看下图
参考资料:http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/