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++中数据结构的多态性示例
- Laravel 仓库 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01