Example of polymorphism working with data structure in C++ based on php example(基于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++中数据结构的多态性示例


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01