“type-switch” construct in C++11

后端 未结 5 1982
自闭症患者
自闭症患者 2020-12-14 04:35

All the time, I find myself doing something like this:

Animal *animal = ...
if (Cat *cat = dynamic_cast(animal)) {
    ...
}
else if (Dog *dog =         


        
5条回答
  •  星月不相逢
    2020-12-14 04:48

    I think you actually want to use inheritance rather than typecasing (I've never seen it before, pretty neat :) ) or type-checking.

    Small example:

    class Animal {
    public:
       virtual void makeSound() = 0; // This is a pure virtual func - no implementation in base class
    };
    
    class Dog : public Animal {
    public:
       virtual void makeSound() { std::cout << "Woof!" << std::endl; }
    }
    
    class Cat : public Animal {
    public:
       virtual void makeSound() { std::cout << "Meow!" << std::endl; }
    }
    
    int main() {
       Animal* obj = new Cat;
    
       obj->makeSound(); // This will print "Meow!"
    }
    

    In this case, I wanted to print the animal-specific sound without specific type checking. To do so, I use the virtual function "makeSound" each subclass of Animal has and overrides to print the correct output for that animal.

    Hope this is what you were aiming for.

提交回复
热议问题