C++对象内存布局–⑧GCC编译器–虚拟继承多个基类

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

//GCC编译器--虚拟继承多个基类.cpp
//2010.8.18
//跟VS的编译器相比,GCC编译器的派生类对象大小就小了很多。
//虚基类表指针合并了,“间隔”也没有了。
//通过另外的测试发现,派生类重写了虚基类的虚函数,但是派生类的虚函数表中有被重写了的虚函数的地址,
//这一点跟VS的编译器不同,可能是因为这样才不需要“间隔”。
//GCC编译器
#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 (*fun)(void*pThis);//非常重要
	/*通过虚函数表调用函数*/
	((fun)(p[0][0]))(p);
	((fun)(p[0][1]))(p);
	((fun)(p[2][0]))(p+2);
	((fun)(p[4][0]))(p+4);
	cout << "证实输出相同的那些函数调用,来自不同的虚函数表表项" << endl;
	cout << &(p[0][0]) << endl;
	cout << &(p[2][0]) << endl;
	cout << &(p[4][0]) << endl;
	//system("pause");
	return 0;
}
/*
sizeof = 24
0x472c50
0x64
0x472c64
0xa
0x472c74
0x14
Derived::f()    100
Derived::ff()   100
Derived::f()    100
Derived::f()    100
证实输出相同的那些函数调用,来自不同的虚函数表表项
0x472c50
0x472c64
0x472c74
*/

原文链接: https://www.cnblogs.com/cswuyg/archive/2010/08/20/1804100.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/14133

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午1:37
下一篇 2023年2月7日 下午1:37

相关推荐