C++虚函数表笔记

关于虚函数以及虚表的介绍网上多如牛毛,就不做累述了,单单就说明下几个关键点

虚函数表是在编译期生成的,其存放位置在代码段中,虚函数按照声明的次序存放

父类的虚函数必定存在于子类的虚函数表中

C++中对象虚函数的调用例如 Derive *f = new Base; f->func(int a, ...) 实际上会被编译成 xxxxfunctionnamexxx(Base *, int, ...) 这类

在编译阶段如果函数是非虚的,那么参数压栈,跳转到函数入口执行。如果是虚函数,则先查表,找到具体的函数入口,再压栈并跳转。

讲解的比较详细博客有 http://blog.csdn.net/linyt/article/details/6336762

#include <iostream>
using namespace std;

void cal() {}

class A{
public:
    virtual void f(int s){ cout<<"Base"<<endl; }
};

class B: public A{
public:
    virtual void f(int s){
        cout<<s<<endl;
    }
};

class C: public A{
public:
    virtual void f(int s){
        cout<<-s<<endl;
    }
};

int bss_seg;
int data_seg = 1;
int data_seg_1 = 2;
int big_data_seg[(int)1e7];

int main() {
    B b;
    A * a = &b;
    a->f(1);
    void (*f)(A*, int) = NULL;
    void*** vt = (void***) a;
    f = (void (*)(A*,int) )( (*vt)[0] );
    f(a, 111);

    int stack_seg;
    int *mmp_seg = new int[200*1024];
    int *heap_seg = new int;

    cout<<&stack_seg<<endl;
    cout<<mmp_seg<<endl;
    cout<<heap_seg<<endl;
    cout<<&bss_seg<<endl;
    cout<<endl;

    cout<<&data_seg<<endl;
    cout<<&data_seg_1<<endl;
    cout<< ( (big_data_seg) ) <<endl;


    cout<<(void*)cal<<endl;
    cout<<(void*)f<<endl;

    C c;
    a = &c;
    a->f(1);
    vt = (void***) a;
    f = (void (*)(A*,int) )( (*vt)[0] );
    f(a, 111);
    cout<<(void*)f<<endl;

    return 0;
}




你可能感兴趣的:(C++虚函数表笔记)