具有多个类对象的 vector 会产生编译错误

Vector with multiple class objects yields a compilation error?

本文关键字:编译 错误 vector 对象      更新时间:2023-10-16

对于下面的类,我想创建一个包含 10 个 Ship() 对象的向量
但是,这会产生以下编译错误,从"int"到"const char*"的转换无效[-fallowive]
(如果我省略矢量行,它可以很好地编译)
我做了一些搜索,找不到答案。

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() 中的向量声明

#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 个同对象的构造,请使用 std::vector第二种构造函数形式

vector<Ship> Shipyard( 10, Ship() ); 
Ship(10)

这将尝试创建一个 Ship 对象并调用构造函数。但是,您的构造函数将string作为参数,因此会出现错误。

要创建 10 Ship 秒的向量,请使用:

vector<Ship> Shipyard(10, Ship());

您正在构造一个值为 10Ship 对象。 由于构造函数采用std::string,因此不能将整数传递给构造函数。

要添加 10 艘船:

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

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