c++ - 没有匹配的成员函数来调用 'push_back'错误

标签 c++ vector composition

//fleet.h 
#include "ship.h"
#include <vector>
#include <iostream>
#ifndef fleet_h
#define fleet_h
using namespace std;

class fleet
{
public:

//Add_ship and remove_ship method
bool add_ship(ship const &s);

private:
vector<ship*> ships;
};

//Add_ship method
bool fleet::add_ship(ship const & s){
    ships.push_back(&s); 
       return true;
}
#endif /* fleet_h */

该程序给我这个错误,我不确定我做错了什么。船对象通过称为add_ship的方法添加到舰队中,该方法使用一个指向船的指针。
No matching member function for call 'push_back'

最佳答案

//Add_ship method bool     
fleet::add_ship(ship const & s)
{ 
    ships.push_back(&s); (No matching member function for call to 'push_back') 
    return true; 
} 

该错误是由于声明:
std::vector<ship*> ships;

vector 包含指向可变船的指针,但是代码将指向const船的指针传递给push_back。您要么需要将const指针存储在 vector 中:
 std::vector<const ship*> ships;

或者将非const指针传递给push_back:
fleet::add_ship(ship & s)
{ 
    ships.push_back(&s); (No matching member function for call to 'push_back') 
    return true; 
} 

旁注:如果您不想出现链接器错误,请将以上函数移至cpp,将其移至类的主体,或将其声明/定义为内联。

关于c++ - 没有匹配的成员函数来调用 'push_back'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52734630/

相关文章:

c++ - 为什么 C++ STL 不实现更高效的 std::set 实现?

c# - 为什么在创建部分关系(组合)时使用嵌套类型

C++ 迭代器和反向迭代器

c - vector 作为参数 C

html - 将矢量图标字体添加到网站标题名称?

kotlin - 如何将依赖项注入(inject) Kotlin 中的接口(interface)委托(delegate)?

perl - Perl 面向对象设计模式

c++ - 用 i++ 或++i 写循环

c++ - 在原生 C/C++ 中使用 Qt 绘制二维码

c++ - 类成员声明的快捷方式