用虚表做些坏事

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()。

 
 
 

猜你喜欢

转载自www.cnblogs.com/buddho/p/10607786.html