将自定义类与向量一起使用:'std::vector'默认构造函数错误

Using custom class with vectors: 'std::vector' default constructor error

本文关键字:std 默认 错误 构造函数 vector 向量 一起 自定义      更新时间:2023-10-16

我试图创建一个定义项目的类和另一个定义库存的类,包含项目的矢量列表。然而,使用下面的解决方案,我得到了多个错误,最明显的是

'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();
};

Item.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);
};

Inventory.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() { ... }

std::vector<>的参考文档(重点是我的)中提到:

T元素的类型
必须满足CopyAssignable和CopyConstructible的要求。
施加在元素上的需求取决于在容器上执行的实际操作。一般要求元素类型为完整类型,且满足Erasable的要求,但许多成员函数的要求更严格。

所以仍然需要提供复制构造函数和赋值操作符。当实例化vector<Item>时,也需要完全声明Item


你可以存储一个智能指针在你的vector虽然,如果不可能为你的类提供所需的功能,例如:

std::vector<std::unique_ptr<Item>> itemlist;

std::vector<std::shared_ptr<Item>> itemlist;

这样做的好处是不需要一直复制Item实例。