没有匹配的成员函数来调用'push_back'错误
No matching member function for call to 'push_back' error
//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 的方法添加到 Fleet,该方法采用指向船舶的指针。
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;
向量包含指向可变船的指针,但代码将指向 const 船的指针传递给push_back
.您要么需要在向量中存储常量指针:
std::vector<const ship*> ships;
或者将非常量指针传递给push_back:
fleet::add_ship(ship & s)
{
ships.push_back(&s); (No matching member function for call to 'push_back')
return true;
}
旁注:如果您不想收到链接器错误,请将上述函数移动到 cpp,将其移动到类的主体,或将其声明/定义为内联。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 错误:"push"的指令后缀无效
- 向量上push方法的C++错误