找出多态对象的大小 [英] Find out the size of a polymorphic object
问题描述
我有一个指针 Base * base_ptr
到一个多态对象。是否可以找出所述对象的动态类型的大小?
I have an pointer Base* base_ptr
to an polymorphic object. Is it possible to find out the size of the dynamic type of said object?
AFAIK, sizeof(* base_ptr)
yilds base_ptr
的静态类型的大小。我开始怀疑这是不可能的,但也许我可以俯瞰某些东西。
AFAIK, sizeof(*base_ptr)
yilds the size of the static type of base_ptr
. I'm beginning to suspect this isn't possible, but maybe I'm overlooking something.
注意:我知道我可以添加一个虚拟函数到我的类型层次结构返回大小,但这不是我的情况下的理想解决方案。
Note: I'm aware that I could add a virtual function to my type hierarchy which returns the size, but this is not a desirable solution in my case.
编辑: sizeof(base_ptr)
- > sizeof(* base_ptr)
推荐答案
不能在C ++中做到这一点 - 至少在可移植的方式。最好的办法是在每个类中实现 getSize()
成员函数。
No, you can't do that in C++ - at least in a portable way. The best bet would be to have getSize()
member function implemented in each class.
这篇关于找出多态对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!