如何使用带向量和共享指针的派生类? [英] How shall I use derived classes with vectors and shared pointers?

查看:174
本文介绍了如何使用带向量和共享指针的派生类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉继承的概念,我很难找到解决以下问题的方法。

I am not familiar with the concept of inheritance, and I am struggling to find a solution to the following problem.

我有2个班,头和手。我主要使用这些类的实例作为向量的元素。这两个类有共同的方法和只有它们特有的方法。

I have 2 classes, Head and Hand. I use instances of these classes mostly as elements of a vector. The two classes have methods in common and methods peculiar only to them.

此外,我处理对象的共享指针。

Moreover, I deal with shared pointers of the object.

我认为实现它的最佳方法是创建一个类BodyPart,就像这样

I thought the best way to implement it was to create a class BodyPart, like this

class BodyPart
{
  public:
  typedef boost::shared_ptr<BodyPart> pointer;

  private:
  int commonMember1;
  double commonMember2;

  public:
  int commonMethod1();
  int CommonMethod2();
}

以及这样的两个派生类

class Hand : public BodyPart
{
  public:
  typedef boost::shared_ptr<Hand> pointer;

  private:
  int numFingers;

  public:
  int getNumFingers();
  void printInfo();
}

最后,我想声明一个BodyPart元素的向量:

Finally, I wanted to declare a vector of BodyPart elements:

std::vector<BodyPart::pointer> cBodyParts;

包含Hand或Head元素,并在需要时在vector元素上调用我的方法。

containing either Hand or Head elements, and call my methods on the vector elements when I need.

但这种方法似乎效果不佳。显然,当我尝试获取向量的元素时,编译器会抱怨它无法从BodyPart共享指针转换为Hand共享指针。此外,如果向量声明如上所述,我不能在其元素上调用特定于派生类的方法(如getNumFinger()),即使实际上是来自该类。

But this approach doesn't seem to work very well. Apparently, when I try to get an element of the vector, the compiler complains that it cannot convert from a BodyPart shared pointer to a Hand shared pointer. Moreover, if the vector is declared like above, I cannot call methods specific to the derived classes (like getNumFinger() ) on its element, even if the actually are from that class.

有没有正确的方法来解决这个问题?或者我的方法完全错了?
提前致谢!

Is there a proper way to deal with this? Or is my approach completely wrong? Thanks in advance!

推荐答案

您的方法是正确的,但编译器也是如此。你有一个基类的共享指针向量,这很好,但你需要转换为实际类型才能获得特定的功能。

Your approach is correct, but so is the compiler. It's good that you have a vector of shared pointers to the base class, but you'll need to cast to the actual type to get specific functionality.

typedef boost :: shared_ptr< Hand>指针; 没用,你只需要基类中的 typedef 。你不会在智能指针之间进行投射。我将基类typedef重命名为

The typedef boost::shared_ptr<Hand> pointer; is useless though, you only need the typedef in the base class. You won't be casting between smart pointers. I'd rename the base class typedef to

typedef boost::shared_ptr<BodyPart> BodyPartPtr;

尽管如此。

Alan在评论中提出了很好的观点:你应该让基类的析构函数虚拟化以防止UB,因为你将通过a删除(间接)指向派生类型的指针指向基本类型的指针。

Good point by Alan in the comments: you should make the base class's destructor virtual to prevent UB, since you'll be deleting (indirectly) pointers to derived types through a pointer to a base type.

这篇关于如何使用带向量和共享指针的派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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