[英]c++ error no matching function
這是我的代碼
#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的錯誤。 我已經包含了內存。 所以我不確定問題是什么。
有兩個問題。
首先,您的向量包含Animal
對象,並且您嘗試使用指向Animal
派生類型的指針填充它。 Animal
和Animal*
的類型不同,因此通常不會編譯操作。
第二, Animal
沒有方法speak()
。 如果您要將派生類型的Animal
推送到向量中,您將獲得對象切片 。 你可以通過讓vector保存到Animal
智能指針來避免它,例如std::vector<std::unique_ptr<Animal>>
。 但是你仍然需要給Animal
一個speak()
虛方法。 例如:
class Animal {
public:
std::string name;
Animal (const std::string& givenName) : name(givenName) {}
virtual std::string speak () = 0;
virtual ~Animal() {}
};
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")) );
}
我在哪里制作了Animal::speak()
一個純虛方法 ,給Animal
一個虛擬析構函數。
查看何時使用虛擬析構函數以及何時虛擬方法應該是純粹的 。
如果你想將Animal*
像skip
它一樣,你應該將你的vector
聲明為vector<Animal*>
。 並且你確實需要指針,以便能夠使用多態。 此外,您的基類動物還需要一個speak()
方法 - 否則您無法在編譯時只知道是Animal
的對象上調用它。 一旦完成這些更改,它應該按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.