虚函数表
#include <iostream>
#include <string>
using namespace std;
class Base1 {
public:
virtual void f(){
cout << "Call Base1::f" << endl;
}
virtual void g(){
cout << "Call Base1::g" << endl;
}
virtual void h(){
cout << "Call Base1::h" << endl;
}
};
class Base2 {
public:
virtual void f(){
cout << "Call Base2::f" << endl;
}
virtual void g(){
cout << "Call Base2::g" << endl;
}
};
class Test: public Base1, Base2{ };
typedef void (*FUN)();
int main(void){
FUN ptr_fun;
long int *ptr;
Base1 base;
long int *ptr_base_vtb = (long int*)&base;
cout << "size of base: " << sizeof(base) << endl;
cout << "address of base: " << &base << endl;
cout << "address of vtb: " << ptr_base_vtb << endl;
ptr = (long int*)*ptr_base_vtb;
ptr_fun = (FUN)ptr[0]; ptr_fun();
ptr_fun = (FUN)ptr[1]; ptr_fun();
ptr_fun = (FUN)ptr[2]; ptr_fun();
// ========================================
Test test;
long int *ptr_test_vtb = (long int*)&test; // &test has type Test*
cout << "size of &test: " << sizeof(&test) << endl; // 8
ptr_test_vtb++;
ptr = (long int*)*ptr_test_vtb;
ptr_fun = (FUN)ptr[0]; ptr_fun();
ptr_fun = (FUN)ptr[1]; ptr_fun();
return 0;
}
输出:
size of base: 8
address of base: 0x7ffe69612258
address of vtb: 0x7ffe69612258
Call Base1::f
Call Base1::g
Call Base1::h
size of &test: 8
Call Base2::f
Call Base2::g