代码之家  ›  专栏  ›  技术社区  ›  Pierre

多态与C++

  •  0
  • Pierre  · 技术社区  · 4 年前

    我正在尝试实现多态性,根据传递给函数的实例调用派生类的特定方法。

    我不确定这是否可行。任何指导都会很有吸引力。

    #include <iostream>
    using namespace std;
    
    class Animal
    {
    public:
        void speak()
        {
            cout << "Base: Animal Speaking!" << endl;
        }
    };
    
    class Dog : public Animal
    {
    public:
        void speak()
        {
            cout << "Dog: Woof!" << endl;
        }
    };
    
    class Cat : public Animal
    {
    public:
        void speak()
        {
            cout << "Cat: Meow!" << endl;
        }
    };
    
    class FarmAnimal : public Animal
    {
    public:
        void speak(Animal *animal)
        {
            animal->speak();
        }
    };
    
    int main()
    {
        Dog dog = Dog();
        Cat cat = Cat();
        FarmAnimal farm_animal = FarmAnimal();
    
        dog.speak();
        cat.speak();
    
        farm_animal.speak(&dog);
        farm_animal.speak(&cat);
    
        return 0;
    }
    

    输出:

    Dog: Woof!
    Base: Meow!
    Base: Animal Speaking!
    Base: Animal Speaking!
    

    Dog: Woof!
    Base: Meow!
    Dog: Woof!
    Cat: Meow!
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   Chris Uzdavinis    4 年前

    当然可以。

    我建议将动物作为“抽象”基类。声明函数 virtual 并通过将它们设置为0(强制派生类重写它们以便能够实例化)使它们成为“纯的”

    class Animal
    {
    public:
        virtual ~Animal() = default; // allows polymorphic destruction too
        virtual void speak() = 0;
    };
    

    class Dog : public Animal
    {
    public:
        void speak() override
        {
            cout << "Dog: Woof!" << endl;
        }
    };
    
    
    class Cat : public Animal
    {
    public:
        void speak() override
        {
            cout << "Cat: Meow!" << endl;
        }
    };
    

    至于 FarmAnimal