C++的虚函数表

 先来看看代码弄清楚继承关系,我写的代码 结论的前两个都是验证正确的,由于结论三相比之下比较复杂,我就把结论三的代码和运行结果分享一下 ,结论一和结论二的代码注释掉了

#include <iostream>
#include <string>
#include <Windows.h>

#define NUMBER 3
using namespace std;

typedef void (*TYPE)(void);


class Father
{
public:
	virtual void fun1()const { cout << "虚函数1" << endl; }
	virtual void fun2()const { cout << "虚函数2" << endl; }
	virtual void fun3()const { cout << "虚函数3" << endl; }
	void fun4()const { cout << "非虚函数" << endl; }
public:
	int x = 200;
	int y = 300;
	// double p = 2.124;
	static int z;
};

int Father::z = 1;


class Mother
{
public:
	virtual void play1()const { cout << __FUNCTION__ << endl; }
	virtual void play2()const { cout << __FUNCTION__ << endl; }
	virtual void play3()const { cout << __FUNCTION__ << endl; }
public:
	int m = 900;
	int p = 250;
};


class Son final : public Father, public Mother
{
public:
	void fun1()const { cout << __FUNCTION__ << endl; }
	virtual void fun5() const { cout << __FUNCTION__ << endl; }
public:
	int z = 500;
};


int
main(int argc, char** argv)
{
	/*
	Father fa; // 虚函数表就在对象中
	cout << "sizeof(fa) = " << sizeof(fa) << endl;

	cout << "father head addr:" << &fa << endl;
	cout << "提取出来的地址:" << (int*)(&fa) << endl;
	// 虚函数表指针的提取  跟个鬼一样  我裂开了
	int* vptr = (int*) * (int*)(&fa);

	for (int i = 0; i < NUMBER; i++) {
		((TYPE)*(vptr + i))();
	}
	// 提取 x y 的值
	cout << "the addr of x:" << &fa.x << endl;
	cout << "the second kind addr of x:"
		<< hex << reinterpret_cast<int>(&fa) + 4 << endl;
	cout << dec << "the value of x:" << fa.x << endl;
	cout << *(int *)(reinterpret_cast<int>(&fa) + 4) << endl;

	cout << "the addr of y:" << &fa.y << endl;
	cout << "the second kind addr of y:"
		 << hex << reinterpret_cast<int>(&fa) + 8 << endl;
	cout << dec << "the value of y:" << fa.y << endl;
	cout << *(int*)(reinterpret_cast<int>(&fa) + 8) << endl;

	string line(50, '-');
	cout << line << endl;
	//继承形式的虚函数表
	Son son;
	Father* father = &son;
	// 提取son对象中的  虚函数表头指针
	int* vaptr = (int*) * (int*)father;
	for (int i = 0; i < NUMBER + 1; i++) {
		((TYPE) * (vaptr + i))();
	}

	for (int i = 0; i < 3; i++) {
		cout << *(int*)((int)father + 4 + i * 4) << endl;
	}
	
	cout << line << endl;
	/*多重继承形式的 虚函数表*/
	Son son2;
	int* vptr2 = (int*) * (int*)& son2;
	for (int i = 0; i < NUMBER + 1; i++) {
		((TYPE) * (vptr2 + i))();
	}

	for (int i = 0; i < 2; i++) {
		cout << *(int*)((int)&son2 + 4 + i * 4) << endl;
	}

	// 取到  mother的 虚函数表指针
	int* ptr = (int*) * (int*)((int)& son2 + 12);

	for (int i = 0; i < NUMBER; i++) {
		((TYPE) * (ptr + i))();
	}
	for (int i = 0; i < NUMBER; i++) {
		cout << *(int*)((int)& son2 + 16 + i * 4) << endl;
	}


	system("pause");
	return 0;
}

结论:

一.普通继承的虚函数表如下图

二。单继承的虚函数表

 补充:

 

三。多重继承的虚函数表

结论三的运行结果:

 

谢谢大家

猜你喜欢

转载自blog.csdn.net/qq_44065088/article/details/104375696
今日推荐