C++对象内存模型

这段代码震撼我妈。。。验证了好多东西

#include <iostream>

using namespace std;

class Base {
    const char ch;
public:
    static int *p1;
    static int *p2;

    Base() : ch('A') {};
private:
    virtual void f1() {
        cout << "base:f1()" << endl;
    }

    virtual void f2() {
        cout << "base:f2()" << endl;
    }
};

class Derived : public Base {
public:
    const int num;

    Derived() : num(100) {};

    virtual void f1() {
        cout << "Derived:f1()" << endl;
    }

    virtual void f2() {
        cout << "Derived:f2()" << endl;
    }
};

typedef void(*func_t)(void);

int main() {
    Derived d{};
    // align with 8 byte
    cout << sizeof(&Derived::f2) << endl;
    cout << "sizeof(long)=" << sizeof(long) << endl;

    long *func_ptr = (long *) *((long *) &d);
    cout << (char) *(((long *) &d) + 2) << endl;
    auto pFunc = (func_t) *(func_ptr + 2);
    pFunc();
}

输出

16 A Derived:f2()

全部评论

相关推荐

评论
1
收藏
分享
牛客网
牛客企业服务