class A{
public:
        virtual void f()
        {
                cout << "A::f()" << endl;
        }
};
class B{
public:
        virtual void f()
        {
                cout << "B::f()" << endl;
        }
};
void test(B*p)
{
        p->f();
}
int main()
{
        A a;
        B b;

        test(&b);

        int *vtbl_a = (int*)(&a);
        int *vtbl_b = (int*)(&b);

        swap(*vtbl_a,*vtbl_b);

        test(&b);
        return 0;
}

  可以看到,第一次调用的是B的f(),第二次我们交换了虚表中的内容,这样发生多态的时候,实际调用的函数是A::f()。


 

 

posted on 2019-03-27 15:20  newbird2017  阅读(122)  评论(0编辑  收藏  举报