抽象类的大小
如何找到抽象类的大小?
class A
{
virtual void PureVirtualFunction() = 0;
};
由于这是一个抽象类,因此我无法创建此类的对象。如何使用“sizeof”运算符找到抽象类 A 的大小?
How can I find the size of an abstract class?
class A
{
virtual void PureVirtualFunction() = 0;
};
Since this is an abstract class, I can't create objects of this class. How will I be able to find the size of the abstract class A using the 'sizeof' operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
sizeof
运算符:You can use the
sizeof
operator:直接的答案是
sizeof
运算符可以采用对象或类型:但实际上,为什么要这样做呢?你问这个问题的事实似乎令人担忧。
The direct answer is that the
sizeof
operator can take either an object or a type:But really, why would you want to do this? The fact that you're asking this seems like cause for concern.
如前所述,这个问题实际上没有意义——实例有大小,但类确实没有。由于无法创建抽象类的实例,因此它的大小基本上是一个毫无意义的概念。您可以使用
sizeof(A)
,但结果并没有多大意义 - 由于空基类优化(举一个明显的例子),sizeof(A)
不一定告诉您使用A
作为基类会对派生类的大小产生多大影响。例如:
如果我在计算机上运行此命令,
sizeof(A)
显示为 1。显而易见的结论是sizeof(Z)
必须至少为 4 - - 但实际上,使用我手头的编译器(VC++、g++),它分别显示为 3 和 1。As stated, the question doesn't really make sense -- an instance has a size, but a class really doesn't. Since you can't create an instance of an abstract class, its size is mostly a meaningless concept. You can use
sizeof(A)
, but the result doesn't mean much -- thanks to the empty base class optimization (for one obvious example),sizeof(A)
does not necessarily tell you how much usingA
as a base class will contribute to the size of a derived class.For example:
If I run this on my computer,
sizeof(A)
shows up as 1. The obvious conclusion would be thatsizeof(Z)
must be at least four -- but in reality with the compilers I have handy (VC++, g++), it shows up as three and one respectively.'sizeof(A)' 工作得很好,你实际上不需要该类的实例。
'sizeof(A)' works just fine, you don't actually need an instance of the class.
不需要创建对象来查找类的大小。您可以简单地执行
sizeof(A)
。There is no need to create object to find the sizeof the class. You can simply do
sizeof(A)
.除了建议使用类名作为
sizeof
的参数的其他答案之外,您还可以声明一个指向抽象类的指针,然后使用
*p
作为参数sizeof
这完全没问题,因为
sizeof
的参数没有被评估。In addition to other answers, which suggested using the name of the class as argument of
sizeof
, you can also declare a pointer to abstract classand then use
*p
as argument insizeof
This is perfrctly fine, since argument of
sizeof
is not evaluated.据我所知,默认情况下抽象类的大小等于 int 的大小。
所以在 32 位机器上,上述类的大小是 4 字节。
As far as I know, by default size of an abstract class is equivalent to the size of int.
so on 32-bit machine size of above class is 4bytes.