具有虚函数的类需要更多的空间 [英] class with virtual functions takes more space

查看:76
本文介绍了具有虚函数的类需要更多的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的代码:

  #include< iostream> 

class A {
int a;
int fun(){}
};

class B {
int a;
virtual int fun(){}
};

int main()
{
std :: cout< sizeof(A)< <尺寸(B) std :: endl;
std :: cin.get();
return 0;
}

输出为:

  4 8 

为什么B类是4个字节任何具有虚函数的类都需要一个指向该类的vtable的指针。

因此,有一个隐藏的成员是指针的大小。



http ://en.wikipedia.org/wiki/Virtual_method_table


There is such code:

#include <iostream>

class A{
    int a;
    int fun(){}
};

class B{
    int a;
    virtual int fun(){}
};

int main()
{
    std::cout << sizeof(A) << " " << sizeof(B) << std::endl;
    std::cin.get();
    return 0;
}

The output is:

4 8

Why class B is 4 bytes bigger than class A?

解决方案

Any class with a virtual function needs a pointer to the vtable for that class. Therefore, there is a hidden member that's the size of the pointer.

http://en.wikipedia.org/wiki/Virtual_method_table

这篇关于具有虚函数的类需要更多的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆