首页 > 解决方案 > Different kind of objects in an array and getting the type of each

问题描述

I am trying to add different types of objects to an array and I want to get the type of the derived class before casting. Is there a nice solution?

BTW.: This example doesn't work. Type is not set correctly when I check the objects.

pseudo code:

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])

**Update: **

I don't understand why this doesn't work.
First, type should be passed to the subclass and is accessible.
Second, I understand why the first and last are 4, but I don't understand why the second elements type is 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;

This returns:

subtype: 4
subtype: 0  
subtype: 4

标签: c++polymorphism

解决方案


As others noted, you can use smart pointers to assure correct destruction and place the base class pointer in the vector. (Note that in my example the range based for needs at least 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;
    }
}

推荐阅读