-2

For the following class I wanted to make a vector with 10 Ship() objects
However this yields the following compilation error invalid conversion from 'int' to 'const char*' [-fpermissive]
( If I omit the vector line it compiles just fine)
I did a little search and could not find an answer.

class Ship
{

protected:
        std::string name;
public:
        Ship(std::string name="Ship")
        {
          std::ostringstream tmp;
          std::string temp;
          tmp << name << ++id;
          name = tmp.str();
        }
};

Vector Declaration in main()

#include <iostream>
#include <vector>
#include <string>
#include "Ship.h"
using std::cout;
using std::endl;
using std::vector;
int main()
{
     vector<Ship> Shipyard; //10% of map dimension is number of ships
     Shipyard.push_back(Ship(10)); //push_back(Ship(),10); doesn't work also
}
solid.py
  • 2,782
  • 5
  • 23
  • 30

3 Answers3

1

You are constructing a Ship object with the value of 10. Since the constructor takes std::string, you cannot pass an integer to the constructor.

To add 10 ships:

std::vector<Ship> ShipYard(10);

or

std::vector<Ship> ShipYard;
ShipYard.resize(10);
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
1

The constructor takes a std::string, but you're passing an integer

For 10 objects construction of same name use this 2nd form of constructor of std::vector :

vector<Ship> Shipyard( 10, Ship() ); 
P0W
  • 46,614
  • 9
  • 72
  • 119
  • vector Shipyard; Shipyard.push_back(10,Ship()); is identical? (because this one yields error) – solid.py Nov 15 '14 at 17:09
  • no matching function for call to 'std::vector::push_back(int, Ship)' – solid.py Nov 15 '14 at 17:12
  • @niCk Did you read the my entire post correctly, I didn't use `push_back`. You just have to use the appropriate constructor – P0W Nov 15 '14 at 17:15
  • This line of code vector Shipyard( 10, Ship() ); yields this error:Undefined reference to 'vtable for Ship' – solid.py Nov 15 '14 at 17:15
  • I read your entire post I just asked for push_back identical syntax but its ok leave it, I deleted the push_back line – solid.py Nov 15 '14 at 17:17
  • @nick Now, this current error is unrelated to your current question, you need to provide more details. Please see [this](http://stackoverflow.com/q/1095298/1870232) post – P0W Nov 15 '14 at 17:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/65003/discussion-between-nick-and-p0w). – solid.py Nov 15 '14 at 17:42
1
Ship(10)

This will try to create one Ship object and call the constructor. However your constructor take string as argument and hence the error.

To create vector of 10 Ships use:

vector<Ship> Shipyard(10, Ship());
rockoder
  • 747
  • 11
  • 23