Windows VStudio 查看虚函数指针

Windows VStudio 查看虚函数指针

  1. 打开VS下面的Developer Command Prompt for VS 2019
    在这里插入图片描述

  2. 切换到当前项目文件下:

    • 切换盘:cd \d C:

    • 切换到当前文件夹下:cd C:\Users\xY\Desktop\test\Project1\

  3. 查看虚函数指针:

    • cl /d1 reportSingleClassLayoutSingingWaiter “1.cpp”

    • 当没有虚继承时:

      在这里插入图片描述

    • 使用虚继承后:

      在这里插入图片描述

完整代码:
#include<iostream>
using namespace std;

// 人类
class Person {
public:
	int m_Age;	// 年龄
};

// 歌手类
class Singer : virtual public Person {

};
// 服务员类
class Waiter : virtual public Person {

};
// 会唱歌的服务员类
class SingingWaiter : public Singer, public Waiter {

};



// 虚继承的实现原理
int main() {

	SingingWaiter sw;
	sw.m_Age = 20;

	// 通过Singer找到偏移量
	cout << "Singer的偏移量: " << *((int*)*(int*)&sw + 1) << endl;
	// 通过Waiter找到偏移量
	cout << "Waiter的偏移量: " << *((int*)*((int*)&sw + 1) + 1) << endl;

	// 获取age的值
	cout << *(int*)((char*)&sw + *((int*)*(int*)&sw + 1)) << endl;

	return 0;
}

结果: