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

标签 c++ vector compiler-errors declaration

对于接下来的类(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/

相关文章:

c++ - 如何使用模板获取 vector 中的数据类型?

c++ - 无法使用 ifstream 读取 txt 文件

c++ - Visual Studio 2010 - 导出(项目)模板菜单选项变灰

c++ - 使用 swap-and-pop 迭代时删除 vector 中的元素

c++ - 对于 std::generate,传递的函数可以使用索引吗?

C++:错误:在 ‘!’ token 之前需要不合格的 ID

c++ - 为什么以及何时使用多态性将基类指向 C++ 中的派生类

java - 如何从哈希表中删除特定日期的数据

c++ - 新手Chrome插件开发人员需要NPAPI入门方面的帮助

java - 如何在Jenkins中修复 “error: cannot find symbol”?