沃梦达 / 编程问答 / php问题 / 正文

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

Example of polymorphism working with data structure in C++ based on php example(基于php示例的C++中数据结构的多态性示例)

本文介绍了基于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

这篇关于基于php示例的C++中数据结构的多态性示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:基于php示例的C++中数据结构的多态性示例

基础教程推荐