No matching member function for call to '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 的方法将船舶对象添加到舰队,该方法采用指向船舶的指针。

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;

向量包含指向可变飞船的指针,但代码将指向常量飞船的指针传递给 push_back。您要么需要在向量中存储 const 指针:

 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,将其移动到 class 的主体,或者 declare/define 将其作为内联,如果您不想出现链接器错误。