gpt4 book ai didi

c++错误没有匹配函数

转载 作者:太空狗 更新时间:2023-10-29 20:28:27 24 4
gpt4 key购买 nike

这是我的代码

#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 的错误。我已经包括内存。所以我不确定是什么问题。

http://pastebin.com/wP6vEVn6是错误信息。

最佳答案

有两个问题。

首先,您的 vector 包含 Animal对象,并且您试图用指向 Animal 的指针填充它派生类型。 AnimalAnimal*类型不同,因此该操作通常无法编译。

第二,Animal没有方法 speak() .如果您要推送 Animal 的派生类型进入 vector ,你会得到object slicing .你可以通过让你的 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一个虚拟析构函数。

参见 when to use virtual destructorswhen should a virtual method be pure .

关于c++错误没有匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13218595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com