对于接下来的类(class),我想制作一个包含 10 个 Ship() 对象的 vector
但是这会产生以下编译错误invalid conversion from 'int' to 'const char*' [-fpermissive]
(如果我省略 vector 线编译就好了)
我做了一点搜索,找不到答案。
class Ship
{
protected:
std::string name;
public:
Ship(std::string name="Ship")
{
std::ostringstream tmp;
std::string temp;
tmp << name << ++id;
name = tmp.str();
}
};
main() 中的 vector 声明
#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
}
最佳答案
构造函数接受一个std::string
,但你传递的是一个整数
对于 同名 的 10 个对象构造,请使用 constructor of std::vector
的第二种形式:
vector<Ship> Shipyard( 10, Ship() );
关于c++ - 具有多个类对象的 vector 会产生编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948339/