C++ inheritance - getClass() equivalent?

后端 未结 3 1702
孤城傲影
孤城傲影 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:42

    I typically create a pure virtual function that each derived class implements to tell you its identity. Example:

    enum AnimalType
    {
       Fish = 0,
       Mammal,
       Bird
    }
    
    class Animal
    {
       virtual AnimalType GetType() const = 0;
    }
    
    ...
    
    AnimalType Bird::GetType()
    {
       return Bird;
    }
    

    Then you can do something like this:

    if (animal.GetType() == Bird)
    {
       // ...
    }
    

提交回复
热议问题