本篇文章給大家分享的是有關帶你了解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; }