//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'
No matching function for call means when we are calling some certain functions, but the id of that function is not matching the argument of the function that is defined. Hence we obtain an error 'no matching function for a call' to C++.
The vector::insert() function in C++ Basically, the vector::insert() function from the STL in C++ is used to insert elements or values into a vector container. In general, the function returns an iterator pointing to the first of the inserted elements.
//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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With