C++对象内存布局⑦VS编译器虚拟继承多个基类

C++对象内存布局--⑦VS编译器--虚拟继承多个基类

 

//VS编译器--虚拟继承多个基类.cpp
//2010.8.18
//测试发现,如果派生类覆盖了基类的虚函数那么被覆盖的虚基类虚函数表前面会有一个0值。
//之前一直没注意到发生重写时会有“间隔”的问题。如要考虑上“间隔”,那么又要复杂上许多。
//这个“间隔”到底用意何在?是否是在多态的时候有所应用?
//猜测可能是一标记。因为派生类重写了虚基类的虚函数,而这个虚函数的地址又没有放在派生类的虚函数表中,
//而且虚拟继承基类跟派生类实例的位置跟普通继承是不同的。
//VS编译器
#include <iostream>
using namespace std;
////////////////////////////////////////////////////
class BaseA
{
	public:
        BaseA(int a = 10):a(a)
        {
        }
		virtual void f()
		{
			cout << "BaseA::f()" << "\t" << a << endl;
		}
		int a;
};
////////////////////////////////////////////////////
class BaseB
{
	public :
        BaseB(int b = 20):b(b)
        {
        }
		virtual void f()
		{
			cout << "BaseB::f()" << "\t" << b << endl;
		}
		int b;
};
////////////////////////////////////////////////////
class Derived :virtual public BaseA, virtual public BaseB
{
	public:
        Derived(int c = 100):c(c)
        {
        }
		void f()
		{
			cout << "Derived::f()" << "\t" << c << endl;
		}
		virtual void ff()
		{
		    cout << "Derived::ff()" << "\t" << c << endl;
		}
		int c;
};
////////////////////////////////////////////////////
int		main()
{
	Derived obj;
	int** p = (int**)&obj;
	cout << "sizeof = " << sizeof(obj) << endl;
	for (int i = 0; i != sizeof(obj)/4; ++i)
	{
	    cout << p[i] << endl;
	}
    typedef void (__thiscall *fun)(void*pThis);//非常重要
	/*通过虚函数表调用函数*/
	((fun)(p[0][0]))(p);
	//((fun)(p[0][1]))();错误
	((fun)(p[4][0]))(p+4);
	((fun)(p[7][0]))(p+7);

	system("pause");
	return 0;
}
/*
sizeof = 36
0041C200
0041C204
00000064
00000000
0041C1F8
0000000A
00000000
0041C1F0
00000014
Derived::ff()   100
Derived::f()    100
Derived::f()    100
请按任意键继续. . .
*/



原文地址:https://www.cnblogs.com/cswuyg/p/1804092.html