//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 */
The program gives me this error and I'm not sure what did I do wrong. ship objects are added to fleet via a method called add_ship, which takes a pointer to a 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;
}
The error is because of the declaration:
std::vector<ship*> ships;
The vector contains pointers to mutable ships, but the code passes a pointer to a const ship to push_back
. You either need to store const pointers in the vector:
std::vector<const ship*> ships;
Or pass a non const pointer to the push_back:
fleet::add_ship(ship & s)
{
ships.push_back(&s); (No matching member function for call to 'push_back')
return true;
}
Side note: move the above function to a cpp, move it to the body of the class, or declare/define it as inline, if you don't want to get linker errors.