数组中不同类型的对象并获取每个对象的类型

时间:2018-10-04 19:58:22

标签: c++ polymorphism

我试图将不同类型的对象添加到数组中,并且我想在转换之前获取派生类的类型。有没有好的解决方案?

顺便说一句:此示例不起作用。检查对象时类型设置不正确。

伪代码:

enum Fruit {
  APPLE = 0,
  BANANA = 1
}

class Fruit {
public:
   int type;
}

class Apple : Fruit {
   ...
}

class Banana : Fruit {
   ...
}

Apple *apple = new Apple();
apple->type = APPLE;

vector<Fruit*> fruits;
fruits.push_back(apple);    

if(fruits[0].type == BANANA)  // type always the same ...
   static_cast<Banana*>(fruits[0])

**更新:**

我不明白为什么这行不通。
首先,应将类型传递给子类并且可以访问。
其次,我了解为什么第一个和最后一个为4,但我不明白为什么第二个元素类型为0?

class PolyTest {
public:
  int type;
};

class SubA : public PolyTest{

};

class SubB : public PolyTest{

};

std::unique_ptr<SubA> sub = std::make_unique<SubA>();
sub->type = 66;

std::unique_ptr<SubB> subb = std::make_unique<SubB>();
sub->type = 3;

std::vector<PolyTest*> tests;
tests.push_back(sub.get());
tests.push_back(subb.get());
sub->type = 4;
tests.push_back(sub.get());

std::cout << "subtype: " << tests[0]->type << std::endl;
std::cout << "subtype: " << tests[1]->type << std::endl;
std::cout << "subtype: " << tests[2]->type << std::endl;

这将返回:

subtype: 4
subtype: 0  
subtype: 4

1 个答案:

答案 0 :(得分:1)

正如其他人所述,您可以使用智能指针来确保正确销毁并将基类指针放置在向量中。 (请注意,在我的示例中,基于的范围至少需要C ++ 11)

class Fruit
{
  public:
    Fruit(int p_type) { type = p_type;};
    int getType() { return type; }
  protected:
    int type;
};

class Banana : public Fruit
{
  public:
    Banana() :Fruit(1) {};
};

class Apple : public Fruit
{
  public:
    Apple() :Fruit(2)  {};
};



int main(int argc, char* argv[]) {
    std::vector<std::shared_ptr<Fruit>> vec;

    auto f1 = std::make_shared<Banana>();
    auto f2 = std::make_shared<Apple>();

    vec.push_back(f1);
    vec.push_back(f2);

    for (auto f : vec)
    {
        std::cout << "my Type is : " << f->getType() << std::endl;
    }
}