找出多态对象的大小

Gab*_*ber 7 c++ polymorphism sizeof

我有一个指向Base* base_ptr多态对象的指针.是否有可能找出所述对象的动态类型的大小?

AFAIK,sizeof(*base_ptr)yilds的静态类型的大小base_ptr.我开始怀疑这是不可能的,但也许我忽视了一些事情.

注意:我知道我可以在我的类型层次结构中添加一个返回大小的虚函数,但在我的情况下这不是一个理想的解决方案.

编辑:sizeof(base_ptr)- >sizeof(*base_ptr)

sha*_*oth 12

不,你不能用C++做到这一点 - 至少以便携方式.最好的选择是getSize()在每个类中实现成员函数.


Luc*_*ore 6

是.您可以在基类中实现一个返回大小的虚函数:

class Base
{
   virtual int size() { return sizeof(Base); }
};
class Derived : public Base
{
   virtual int size() { return sizeof(Derived); }
};

//......
Base* b = new Derived;
int size = b->size(); //will call Derived::size() and return correct size
Run Code Online (Sandbox Code Playgroud)