zoukankan      html  css  js  c++  java
  • C++对象内存布局②测试派生类跟基类的虚函数表

    C++对象内存布局--②测试派生类跟基类的虚函数表

     测试2:父类虚函数表跟子类虚函数表是不同的。 

    //派生类跟基类的虚函数表.cpp
    //2010年8月18日
    //测试说明,父类虚函数表跟子类虚函数表是不同的。理解C++对象的内存布局
    //VS编译器
    #include <iostream>
    using namespace std;
    //////////////////////////////////////////////////////////////////
    class Base
    {
    public:
    Base():b(
    10)
    {
    }
    virtual void show()
    {
    cout
    << "Base::show()" << endl;
    }
    private:
    int b;
    };
    //////////////////////////////////////////////////////////////////
    class Derived : public Base
    {
    public:
    Derived():c(
    20)
    {
    }
    void show()
    {
    cout
    << "Derived::show()" << endl;
    }
    private:
    int c;
    };
    //////////////////////////////////////////////////////////////////
    int main()
    {
    Base a_obj;
    int** p = (int**)&a_obj;
    typedef
    void (__thiscall *fun)(void*pThis);//非常重要//虚函数表指针->虚函数表->调用虚函数
    ((fun)(p[0][0]))(p);
    cout
    << "虚函数表地址 = 0x" << p[0] << endl;
    cout
    << "私有成员变量 = 0x" << p[1] << endl;

    Derived b_obj;
    int** pp = (int**)&b_obj;
    ((fun)(pp[
    0][0]))(pp);//虚函数表指针->虚函数表->调用虚函数
    cout << "虚函数表地址 = 0x" << pp[0] << endl;
    cout
    << "私有成员变量 = 0x" << pp[1] << endl;
    cout
    << "私有成员变量 = 0x" << pp[2] << endl;
    system(
    "pause");
    return 0;
    }
    /*
    Base::show()
    虚函数表地址 = 0x0041C248
    私有成员变量 = 0x0000000A
    Derived::show()
    虚函数表地址 = 0x0041C260
    私有成员变量 = 0x0000000A
    私有成员变量 = 0x00000014
    请按任意键继续. . .
    */

     

  • 相关阅读:
    echo和tee的使用
    cut列的截取
    BZOJ1414: [ZJOI2009]对称的正方形(二维hash)
    BZOJ1010: [HNOI2008]玩具装箱toy
    BZOJ2588: Spoj 10628. Count on a tree(主席树)
    BZOJ3991: [SDOI2015]寻宝游戏(set+lca / 虚树)
    BZOJ2286: [Sdoi2011]消耗战(虚树)
    Linux
    奇妙的棋盘(建图+搜索)
    礼物(动态规划)
  • 原文地址:https://www.cnblogs.com/cswuyg/p/1804077.html
Copyright © 2011-2022 走看看