Example of polymorphism working with data structure in C++ based on php example

前端 未结 3 1772
日久生厌
日久生厌 2021-01-28 21:52

I am learning polymorphism and I am familiar with php.

I came across this excellent example from https://stackoverflow.com/a/749738/80353. reproduced below.

How

3条回答
  •  温柔的废话
    2021-01-28 22:27

    Since you only asked about storing them, I'll omit the implementation of Animal, Dog and Cat.

    vector< shared_ptr > animals;
    animals.push_back( new Dog("Skip") );
    animals.push_back( new Cat("Snowball") );
    
    for( size_t i = 0; i< animals.size(); ++i )
        cout << animals[i]->name << " says: " << animals[i]->speak() << endl;
    

    Essentially you need to store pointers to the objects. Put simply, shared_ptr is a class that stores a pointer and deletes it when it is no longer referenced.

提交回复
热议问题