使用基类指针查找派生类对象的大小 [英] find size of derived class object using base class pointer

查看:252
本文介绍了使用基类指针查找派生类对象的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你不知道派生类型时,可以使用基类指针来找到派生类对象的大小。

Is it possible to find the size of a derived class object using a base class pointer, when you don't know the derived type.

谢谢。 / p>

Thank you.

推荐答案

没有直接的方法,但你可以写一个虚拟 size()方法子类可以实现。中间模板类可以自动化腿部工作。

There's no direct way, but you can write a virtual size() method child classes can implement. An intermediary templates class can automate the leg work.

struct base {
  virtual size_t size() const =0;
  virtual ~base() { }
};

template<typename T> 
struct intermediate : base {
  virtual size_t size() const { return sizeof(T); }
};

struct derived : intermediate<derived> 
{ };

这需要您的层次结构是多态的...但是,请求基于动态类型的行为对象而不是其静态类型是多态行为的定义的一部分。所以这不会添加一个v表到一般的用例,因为至少你可能已经有一个虚拟析构函数。

This does require your hierarchy be polymorphic... however, requesting behavior based on the dynamic type of an object rather than its static type is part of the definition of polymorphic behavior. So this won't add a v-table to the average use case, since at the very least you probably already have a virtual destructor.

这个特定的实现限制你的继承树到单个级别而不进入多重继承[即,从派生的类型将不会获得自己的大小]。有一个略微更复杂的变体,绕过这个。

This particular implementation does limit your inheritance tree to a single level without getting into multiple inheritance [ie, a type derived from derived will not get its own override of size]. There is a slightly more complex variant that gets around that.

struct base { /*as before */ };

template<typename Derived, typename Base>
struct intermediate : Base {
  virtual size_t size() const { return sizeof(Derived); }
};

struct derived : intermediate<derived, base>
{ };

struct further_derived : intermediate<further_derived, derived>
{ };

基本上,这将在中间您的层次结构的每个实际层,每个覆盖 size ,具有适当的行为,并从实际基本类型派生。重复广告。

Basically, this inserts an intermediate in between each actual layer of your hierarchy, each overriding size with the appropriate behavior, and deriving from the actual base type. Repeat ad nauseum.

//what you want
base >> derived 
     >> more_deriveder
     >> most_derivedest

//what you get
base >> intermediate<derived, base> 
     >> derived >> intermediate<more_deriveder, derived> 
     >> more_deriveder >> intermediate<most_derivedest, more_deriveder> 
     >> most_derivedest

几个mixin类型库使用这样的方案,以便可以将mixins添加到不引入多重继承的现有层次结构。就个人而言,我很少使用单一级别的继承,所以我不介意额外的复杂性,但你的里程可能会有所不同。

Several mixin-type libraries make use of such a scheme, such that the mixins can be added to an existing hierarchy without introducing multiple inheritance. Personally, I rarely use more than a single level of inheritance, so I don't bother with the added complexity, but your mileage may vary.

这篇关于使用基类指针查找派生类对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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