C++ inheritance - getClass() equivalent?

后端 未结 3 1717
孤城傲影
孤城傲影 2021-02-20 13:12

Take the following C++ for example.

vector listAnimal;

class Fish : Animal ...
class Mammal : Animal ...
class Bird : Animal ...

3条回答
  •  太阳男子
    2021-02-20 13:28

    A container only stores elements of a fixed type, you want a pointer to an object.

    #include 
    #include 
    
    std::vector> animal_list;
    
    animal_list.emplace_back(new Fish);
    animal_list.emplace_back(new Mammal);
    animal_list.emplace_back(new Bird );
    

    Store Animal type in vector will cause object slice when push derived types into listAnimal.

     vector listAnimal;
     listAnimal.push_back(Fish);  // Fish is sliced to Animal, no fish for you.
    

    Edit:

    To know what type a derived animal is, you could store it in a member

    Enum AnimalType
    {
      FISH,
      MAMAL,
      BIRD
    };
    
    class Animal
    {
    public:
      Animal(AnimalType animal_type) : type(animal_type) {}
      AnimalType GetType() const { return type; }
    private:
      AnimalType type;   
    };
    

提交回复
热议问题