继承里既有虚继承也有虚函数继承(即既有虚基表,也有虚函数表)

对于单一的虚继承可参考这篇博客:
https://blog.csdn.net/sophia__yu/article/details/82791522
对于有虚函数继承可参考这篇博客:
https://blog.csdn.net/sophia__yu/article/details/82791592
接下来将会介绍既有虚继承也有多态的继承:
首先看代码:

#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
/////////////虚基表和虚表
class A
{
public:
	virtual void f1()
	{
		cout << "A::f1()" << endl;
	}
	virtual void f2()
	{
		cout << "A::f2()" << endl;
	}
public:
	int _a;
};
class B :virtual public A
{
public:
	virtual void f1()  //重写虚函数
	{
		cout << "B::f1 ()" << endl;
	}
	virtual void f3()  // B重新定义的虚函数
	{
		cout << "B::f3()" << endl;
	}
	//另外B继承了A的f2函数
public:
	int _b;
};
class  C : virtual public A
{
public:
	virtual void f1()  // C重写了虚函数f1
	{
		cout << "C::f1()" << endl;
	}
	virtual void f3()  // C重新定义了虚函数f3
	{
		cout << "C::f3()" << endl;
	}
	//另外C继承了A的虚函数f2
public:
	int _c;
};
class D : public B, public C
{
public:
	virtual void f1()
	{
		cout << "D::f1()" << endl;
	}
	virtual void f4()
	{
		cout << "D::f4()" << endl;
	}
public:
	int _d;
};
typedef void(*FUNC)();

void printVtable(int *vfter)
{
	cout << "虚表地址:" << vfter << endl;
	for (int i = 0; vfter[i] != 0; i++) //因为虚表最后一个元素是0
	{
		printf("第%d个虚函数地址:0x%x,->", i, vfter[i]);
		FUNC f = (FUNC)vfter[i];
		f(); //调用该虚函数
	}
	cout << endl;
}
int main()
{
	D d;
	d._a = 1;
	d._b = 2;
	d._c = 3;
	d._d = 4;
	cout << sizeof(d) << endl;
	int *vfptr1 = (int*)(*((int*)(&d))); //B 的虚表指针
	printVtable(vfptr1);
	int *vfptr2 = (int*)(*((int*)(((char*)(&d)) + 12)));//  C的虚表指针
	printVtable(vfptr2);
	int *vfptr = (int*)(*((int*)(((char*)(&d)) + 28)));  //  公共虚表指针
	printVtable(vfptr);
	system("pause");
	return 0;
}

在这里插入图片描述
具体解释如下:
在这里插入图片描述
注:主要是在A类中,不论是不是冗余数据,都要放在公共数据块即最下边(相对编译器)。

猜你喜欢

转载自blog.csdn.net/sophia__yu/article/details/82946074
今日推荐