基于php示例的C++中数据结构的多态性示例

2022-01-24 00:00:00 polymorphism php c++

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 do I write the same code, but in C++?

I have a problem writing it myself because I believe (I may be wrong) that the data structures in C++ are strict.

You must have all the elements inside a linkedlist or array in C++ of the same type.

So I believe that you need to store the cat and dog as their base class into the data structure.

So how do I write this php code snippet into a C++ code snippet that uses a strict data structure that it can only store elements of 1 data type?

class Animal {
    var $name;
    function __construct($name) {
        $this->name = $name;
    }
}

class Dog extends Animal {
    function speak() {
        return "Woof, woof!";
    }
}

class Cat extends Animal {
    function speak() {
        return "Meow...";
    }
}

$animals = array(new Dog('Skip'), new Cat('Snowball'));

foreach($animals as $animal) {
    print $animal->name . " says: " . $animal->speak() . '<br>';
}

解决方案

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

#include <iostream>
#include <vector>
#include <memory>

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<std::unique_ptr<Animal>> animals;
    animals.push_back( std::unique_ptr<Animal>(new Dog("Skip"))  );
    animals.push_back( std::unique_ptr<Animal>(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

相关文章