C 错误无匹配函数
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’
我想做的:
我只想使用一个动态的数据结构,该数据结构将通过可能的动物对象列表。
我试图在C 语法中学习这种多态性概念。
我熟悉Java和PHP,但对于C 而言,
少得多。更新:
我添加了其中一个答案所述的更改。http://pastebin.com/9anijwzq
但是我遇到了有关unique_ptr的错误。我包括内存。所以我不确定问题是什么。
http://pastebin.com/wp6vevn6是错误消息。
有两个问题。
首先,您的向量包含Animal
对象,您正在尝试用指针填充Animal
派生类型。Animal
和Animal*
不是相同的类型,因此通常不会编译操作。
第二,Animal
没有方法speak()
。如果要将Animal
的派生类型推入向量,则将获得对象切片。您可以通过让矢量持有智能指针到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()
a 纯虚拟方法并给定的Animal
虚拟破坏者。
请参阅何时使用虚拟破坏者,何时应该纯虚拟方法。
如果要将Animal*
像skip
一样,则应将vector
声明为vector<Animal*>
。而且您确实想要其中的指针,以便能够使用多态性。此外,您的基类动物还需要speak()
方法 - 否则您将无法在编译时间仅知道为Animal
的对象上调用该方法。一旦进行了这些更改,它应该按照您的期望工作。
相关文章:
- Rcpp并行无匹配函数,用于调用"转换"
- 为什么通过带有文字编号的引用调用会出现"无匹配函数"错误?
- 无匹配函数呼叫getline()
- 错误:呼叫构造器的匹配函数无匹配功能
- C 线程 - 无匹配函数供呼叫
- C 汇编错误:无匹配的构造函数以进行初始化
- 错误代码:无匹配函数供呼叫
- 为链接列表构建迭代器类(错误:无匹配的构造函数以初始化)
- 子类/超类的"无匹配函数调用"
- 无匹配函数呼叫
- 与(C )无匹配函数
- 将迭代器作为参数传递时无匹配的函数调用
- 无匹配函数呼叫
- 无匹配函数呼叫(类,C )
- C 11无匹配函数,可以呼叫'std :: vector
- 对矢量对:无匹配函数
- C 在较旧的JSON :: NLOHMANN库中使用push_back时无匹配函数
- std::查找"错误无匹配函数"
- C 错误无匹配函数
- 将STD向量作为参考:无匹配函数要呼叫