这是我的代码
#include <iostream>
#include <vector>
#include <memory>
#include <tr1/memory>
using namespace std;
class Animal {
public:
string name;
Animal (const std::string& givenName) : name(givenName) {
}
};
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() {
vector<Animal> animals;
Dog * skip = new Dog("Skip");
animals.push_back( skip );
animals.push_back( new Cat("Snowball") );
for( int i = 0; i< animals.size(); ++i ) {
cout << animals[i]->name << " says: " << animals[i]->speak() << endl;
}
}
这些是我的错误:
index.cpp: In function ‘int main()’:
index.cpp:36: error: no matching function for call to ‘std::vector<Animal, std::allocator<Animal> >::push_back(Dog*&)’
/usr/include/c++/4.2.1/bits/stl_vector.h:600: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Animal, _Alloc = std::allocator<Animal>]
index.cpp:37: error: no matching function for call to ‘std::vector<Animal, std::allocator<Animal> >::push_back(Cat*)’
/usr/include/c++/4.2.1/bits/stl_vector.h:600: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Animal, _Alloc = std::allocator<Animal>]
index.cpp:40: error: base operand of ‘->’ has non-pointer type ‘Animal’
index.cpp:40: error: base operand of ‘->’ has non-pointer type ‘Animal’
我想做的事:
我只想使用一个动态数据结构来遍历可能的 Animal 对象列表。
我正在尝试在 C++ 语法中学习这种多态性概念。
我熟悉 Java 和 PHP,但对 C++ 则不太熟悉。
更新:
我已经添加了其中一个答案提到的更改。http://pastebin.com/9anijwzQ
但是我收到有关 unique_ptr 的错误。我已经包含了内存。所以我不确定问题是什么。