c++ - 具有虚拟参数的 C++ 类中的差异 sizeof

标签 c++ class virtual sizeof

我有这个代码:

#include <stdio.h>

class CoolClass
{
   public:
      virtual void set(int x){x_=x;};
      virtual int get(){return x_;};

   private:
      int x_;
};

class PlainOldClass
{
   public:
      void set(int x){x_=x;};
      int get(){return x_;};

   private:
      int x_;
};

int main ()
{
   printf("CoolClass:\t %ld \nPlainOldClass:\t %ld \n",
          sizeof(CoolClass),sizeof(PlainOldClass)); 

   return 0;
}

输出是:

CoolClass:   16 
PlainOldClass:   4 

我想知道为什么会这样,我试图找到一些关于虚拟的信息,但我不明白。

非常感谢!

最佳答案

发生这种情况是因为具有虚函数的类通常由编译器通过 virtual table 实现,另见 this explanation .为了使用这样的虚拟表,它们在内部存储了一个指向该表的指针。在您的情况下, CoolClass 的大小由 int 成员的大小(通常为 4 个字节)加上指针的大小(通常为 4 或 8 个字节,取决于架构:32 位与 64 位)。由于填充,您看到 16。

关于c++ - 具有虚拟参数的 C++ 类中的差异 sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490643/

相关文章:

c++ - 显式模板特化不能有存储类 - 成员方法特化

C++ 头文件和类文件 - undefined reference

c++ - 关于C++虚拟继承的问题

apache - XAMPP 虚拟主机不工作

c++ - 使从一个基类派生的类能够使用继承的 protected 成员

c++ - 转发元组的一个元素

c++ - 静态库大小近 400MB

c++ - 根据解析的字符串创建对象

ruby-on-rails - 为什么 Rails 模型中的新类方法结果为零?

c# - 静态变量是否在类实例之间共享