本篇文章给大家分享的是有关带你了解C++ 中的虚函数,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

先从对象大小开始
假设我们有如下代码,假设 int 占 4 字节,指针占 4 字节。
#include "stdafx.h"
#include "stdlib.h"
#include "stddef.h"
class CBase
{
public:
virtual void VFun1() { printf(__FUNCTION__ "\n"); }
virtual void VFun2() { printf(__FUNCTION__ "\n"); }
virtual ~CBase() { printf(__FUNCTION__ "\n"); }
int data;
};
class CDerived : public CBase
{
public:
virtual void VFunNew() { printf(__FUNCTION__ "\n"); }
virtual void VFun1() override { printf(__FUNCTION__ "\n"); }
virtual ~CDerived() override { printf(__FUNCTION__ "\n"); }
};
int _tmain(int argc, _TCHAR* argv[])
{
printf("sizeof CBase is: %d, offset of data is %d\n",
sizeof(CBase), offsetof(CBase, data));
system("pause");
CBase* pBase = new CDerived();
pBase->VFun1();
pBase->VFun2();
system("pause");
return 0;
}