没有匹配的成员函数来调用“ push_back”错误

时间:2018-10-10 07:13:59

标签: 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'

1 个答案:

答案 0 :(得分:4)

//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。您要么需要将const指针存储在向量中:

 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,将其移至类的主体,或将其声明/定义为内联。