[範例 Code] Vector 內部物件,使用多型。

classes hierachy
#include <iostream>

class Animal
{public:
    virtual void cry_out() = 0;
};

class Cat : public Animal
{public:
    void cry_out(){ std::cout << "Meow! Meow!" << std::endl; }
};

class Dog : public Animal
{public:
    void cry_out(){ std::cout << "Woof! Woof!" << std::endl; }
};
main
#include <vector>
#include <memory> // shared_ptr
#include <algorithm> // for_each

int main()
{    
    std::vector<std::shared_ptr<Animal>> animals = 
    {
        // new Cat(), // compile error
        std::make_shared<Cat>(), // use helper function
        std::shared_ptr<Dog>(new Dog()) // or use smart poionter constructor
    };
    
    std::for_each(animals.cbegin(), animals.cend(), 
        [](const std::shared_ptr<Animal>& animal){
           animal->cry_out();
        }
    );

   return 0;
}
Output
Meow! Meow!
Woof! Woof!
comments powered by Disqus