带你了解C++中的虚函数-创新互联

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

成都网站建设公司更懂你!创新互联只做搜索引擎喜欢的网站!成都网站制作前台采用搜索引擎认可的DIV+CSS架构,全站HTML静态,H5开发+CSS3网站,提供:网站建设,微信开发,微信小程序开发购物商城网站建设重庆APP软件开发域名申请,服务器租售,网站代托管运营,微信公众号代托管运营。

先从对象大小开始

假设我们有如下代码,假设 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;
}

网页名称:带你了解C++中的虚函数-创新互联
标题来源:http://myzitong.com/article/dgphhd.html