C++改变虚指针指向的虚表

C++可以改变指针指向的虚表,但不能改变虚表里面的内容,即虚函数的地址。

#include 

using namespace std;

class A
{
public:
    A():m_a(1){}
    int m_a;
    virtual void f(){ cout << "A   fun "<class B
{
public:
    B() :m_b(2){}
    int m_b;
    virtual void f(){ cout << "B  fun " <class C
{
public:
    C():m_c(3){}
    int m_c;
     void f(){ cout << "C fun " << m_c << endl; }
};

class D : public C
{
public:
    D():m_d(4){}
    int m_d;
    void f(){
        cout << "D fun " << m_d << endl;
    }
};

int main()
{
    A* a = new A;
    a->f();
    cout << sizeof(a) << endl;
    /*B* b = dynamic_cast(a);
    if (b)
    {
        cout << "b is not null" << endl;
    }
    else
    {
        cout << "b is null" << endl;
    }*/

    int* vptr = reinterpret_cast<int*>(a);
    cout <static_cast(static_cast<void*>(a));
    bb->f();
    cout <new B;
    b1->f();

    *vptr = *reinterpret_cast<int*>(b1);//改变a对象的虚指针地址,指向b1的虚表

    bb = static_cast(static_cast<void*>(a));
    bb->f();



    /*C* c = new D;
    c->f();
    D* d = static_cast(c);
    d->f();*/
    /*D* dd = dynamic_cast(c);
    dd->f();*/

    /*C* c = new C;
    c->f();
    D* d = static_cast(c);
    d->f();*/


    return 0;
}

你可能感兴趣的:(C++)