c++ 对象模型 例子:
//Base.h文件
#pragma once
#include<string>
#include<iostream>
using namespace std;
class Base
{
public:
Base();
void fun();
static void s_fun();
static void s_fun2();
virtual void v_fun();
virtual ~Base();
virtual void v_fun2();
private:
int count =123;
int count2 =456;
static int s_count;
};
//Base.cpp文件
#include "Base.h"
Base::Base()
{
}
void Base::fun()
{
cout << "fun" << endl;
}
void Base::s_fun()
{
cout << "s_fun" << endl;
}
void Base::s_fun2()
{
cout << "s_fun2" << endl;
}
void Base::v_fun()
{
cout << "v_fun" << endl;
}
Base::~Base()
{
}
void Base::v_fun2()
{
cout << "v_fun2" << endl;
}
//main.cpp
#include<iostream>
#include"Base.h"
using namespace std;
int main()
{
Base base;
//1,地址 对应的对象位置
cout << "对象大小:"<<sizeof(base) << endl;
cout << "对象首地址:"<<(int*)(&base)<<endl;
cout << "对象首地址的值(存放的是:虚函数表的首地址):" << (int*)*(int*)(&base) << endl;
cout << "虚函数表:" << endl;
cout << "虚函数表 — 第1个函数地址:" << (int*)*((int*)*(int*)(&base) + 0) << endl; //virtual void v_fun();
cout << "虚函数表 — 第2个函数地址:" << (int*)*((int*)*(int*)(&base) + 1) << endl; //virtual ~Base();
cout << "虚函数表 — 第3个函数地址:" << (int*)*((int*)*(int*)(&base) + 2) << endl; //virtual void v_fun2();
cout << "count成员 — 地址:" << (int*)((int*)(&base)+1) << endl;
cout << "count2成员 — 地址:" << (int*)((int*)(&base) + 2) << endl;
//2,地址转换成对应对象
typedef void(*FUN)(void);
FUN f1 = (FUN)*((int*)*(int*)(&base) + 0);
f1();
//(FUN)*((int*)*(int*)(&base) + 1); 因为是一个析构函数 所以不做处理
FUN f2 = (FUN)*((int*)*(int*)(&base) + 2);
f2();
int* coun = (int*)((int*)(&base) + 1);
cout << "coun:" << *coun << endl;
int* coun2 = (int*)((int*)(&base) + 2);
cout << "coun2:" << *coun2 << endl;
return 0;
}