虚函数内存模型

// 理解虚函数在内存中的实现

#include 

class Base
{
public:
	Base() {printf("Base\n");}
	virtual ~Base() {printf("~Base\n");}
public:
	virtual void f() {printf("Base:f\n");}
	virtual void g() {printf("Base:g\n");}
	int m_nBase;
};

class Derive : public Base
{
public:
	Derive() {printf("Derive\n");}
	~Derive() {printf("~Derive\n");}
public:
	void f() {printf("Derive:f\n");}
	void g() {printf("Derive:g\n");}
	int m_nDerive;
};

typedef void (*FUN)(void);

int main()
{
	Base* pB = new Base;
	Base* pD = new Derive;

	int nB = sizeof(Base);
	int nD = sizeof(Derive);

	pB->f();
	pD->f();

	pB->g();
	pD->g();

	// 获取虚函数表的地址
	int* pBvftab = (int*)*(int*)pB;

	// 0为析构函数,1为f(),2为g()
	FUN fBF = (FUN)*(pBvftab + 1);
	fBF();

	FUN fBG = (FUN)*(pBvftab + 2);
	fBG();

	int* pDvftab = (int*)*(int*)pD;

	FUN fDF = (FUN)*(pDvftab + 1);
	fDF();

	FUN fDG = (FUN)*(pDvftab + 2);
	fDG();

	delete pB;
	delete pD;

	return 0;
}


虚函数表指针在内存中的最前面

运行结果图:


发布了128 篇原创文章 · 获赞 142 · 访问量 28万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览