c++ - 使用带有 vector : 'std::vector' default constructor error 的自定义类

标签 c++ c++11 vector

我正在尝试创建一个定义项目的类和另一个定义库存的类,其中包含项目的 vector 列表。但是,使用下面的解决方案,我遇到了多个错误,最明显的是

'std::vector': no appropriate default constructor available

...以及其他我只能假定从中引出的内容。这是我的定义:

header.h

#include <iostream>
#include <string>
#include <vector>
#include "Item.h"
#include "Inventory.h"

Item.h

#include "header.h"
class Item
{
private:
    std::string name;
public:
    Item(std::string n, std::string d, int c);
    std::string getName();
};

项目.cpp

#include "header.h"
using namespace std;

Item::Item(string n)
{
    name = n;
}

string Item::getName()
{
    return name;
}

Inventory.h

#include "header.h"

class Inventory
{
private:
    std::vector<Item> itemlist;

public:
    Inventory();
    std::string getInventory();
    void addItem(Item x);
};

库存.cpp

#include "header.h"
using namespace std;

Inventory::Inventory()
{
}

string Inventory::getInventory()
{
    string output = "";

    for (int i = 0; i <= itemlist.size(); i++)
    {
        output = output.append(itemlist[i].getName());
    }

    return output;
}

void Inventory::addItem(Item x)
{
    itemlist.push_back(x);
}

我感觉这与我的自定义对象以某种方式与我尝试使用它们的方式不兼容有关。所有这一切是否存在根本性错误,或者我只是在某个地方犯了一个简单的错误?

添加一个默认构造函数没有任何改变,但是添加一个 : itemlist(0) 初始化器到 Inventory 构造函数消除了那个特定的错误。但是,这两个错误的多个实例仍然发生:

'Item': undeclared identifier

'std::vector': 'Item' is not a valid template type argument for parameter '_Ty'

我想知道关于我的两个单独的类,这里是否发生了某种范围问题?

最佳答案

您需要有默认构造函数才能使用 std::vector。默认构造函数是没有参数的构造函数,即 Item::Item() { ... }

关于c++ - 使用带有 vector : 'std::vector' default constructor error 的自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33109791/

相关文章:

c++ - 具有可变参数模板的类成员函数继承

python - 如何以 3D 形式绘制 2 个向量

c++ - 使用正则表达式获取大括号 block 的列表

c++ - 为什么此模板参数推断失败?

c++ - 在 C++11 中,是否可以从具有指定模板参数的模板类中获取通用模板类?

c++ - 我应该如何命名这些类?

java - 使用外部变量更改数组的内容

c++ - 迭代多个嵌套 vector

另一个 header 中的 C++ 结构函数给出 "missing type specifier"

c++ - 读取映射到内存的 CSV 文件的最简单方法?