#include <iostream>
using namespace std;
class Father {
public:
virtual void func1() { cout << "Father::func1" << endl; }
virtual void func2() { cout << "Father::func2" << endl; }
virtual void func3() { cout << "Father::func3" << endl; }
void func4() { cout << "Father::func4" << endl;}
public:
int x = 1;
int y = 2;
static int z;
};
typedef void(*func_t) (void); //函数指针 返回类型void ,参数void
int Father::z = 1;
int main(void) {
Father father;
// 含有虚函数的对象的内存中,最先存储的就是“虚函数表”
cout << "对象地址:" << (long long*)&father << endl;
//对象的地址就是虚函数表的地址
//&father 是一个 Father* 类型的地址(指向对象的首地址) ,\
转为int* 类型.
long long* vptr = (long long*)*(long long*)&father;
//&father (int*)&father int类型的father指针, \
// *(int*)&father;int类型的整数
//(int*)*(int*)&father //把int型转成 int*型\
(目的是让编译器通过,值并没有改变)
cout << "虚函数表指针vptr:" << vptr << endl;
cout << "调用第1个虚函数: ";
((func_t)*vptr)();
cout << "调用第2个虚函数:";
((func_t) * (vptr + 1))();
cout << "调用第3个虚函数: ";
((func_t) * (vptr + 2))();
//验证vptr下面是不是数据成员x和y
cout << "第1个数据成员的地址: " << endl;
cout << &father.x << endl;
cout << std::hex << (long long)(&father) + 8 << endl; //std::hex 十六进制
cout << (int*)((long long)(&father) + 8) << endl;
cout << "第1个数据成员的值:" << endl;
cout << std::dec << father.x << endl; //std::dec 十进制 可不加
cout << *(int*)((long long)(&father) + 8) << endl;//外挂就是这样访问,直接操控指针
cout << "第2个数据成员的地址: " << endl;
cout << &father.y << endl;
cout << std::hex << (int)&father + 12 << endl;
cout << "第2个数据成员的值:" << endl;
cout << std::dec << father.y << endl;
cout << *(int*)((long long)&father + 12) << endl;
cout << "sizeof(father) == " << sizeof(father) << endl;
//16 两个非静态成员变量 占8 ,64位下虚函数表指针恒为8,\
指向虚函数表
Father father2;
cout << "father的虚函数表:";
cout << *(long long*)(*(long long*)&father) << endl;
cout << "father2的虚函数表:";
cout << *(long long*)(*(long long*)&father2) << endl;
//不同对象 使用同一张虚函数表
system("pause");
return 0;
}