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

前端 未结 3 1776
日久生厌
日久生厌 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条回答
  •  猫巷女王i
    2021-01-28 22:26

    As someone not familiar with C++, create a index.cpp file and fill it up with the following

    #include 
    #include 
    #include 
    
    using namespace std;
    
    class Animal {
      public:
        std::string name;
        Animal (const std::string& givenName) : name(givenName) {}
        virtual string speak () = 0;
        virtual ~Animal() {}
    
      };
    
    class Dog: public Animal {
      public:
        Dog (const std::string& givenName) : Animal (givenName) {
    
        }
        string speak ()
          { return "Woof, woof!"; }
      };
    
    class Cat: public Animal {
      public:
        Cat (const std::string& givenName) : Animal (givenName) {
        }
        string speak ()
          { return "Meow..."; }
      };
    
    int main() {
        std::vector> animals;
        animals.push_back( std::unique_ptr(new Dog("Skip"))  );
        animals.push_back( std::unique_ptr(new Cat("Snowball"))  );
    
        for( int i = 0; i< animals.size(); ++i ) {
            cout << animals[i]->name << " says: " << animals[i]->speak() << endl;
        }
    
    }
    

    afterwards, compile the index.cpp file with the following command

    c++ index.cpp -std=c++11 -stdlib=libc++
    

    you need that because of the use of smart pointers unique_ptr in the code.

    finally you can execute the compiled executable output file which should be a.out

    ./a.out
    

提交回复
热议问题