gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:36:06 25 4
gpt4 key购买 nike

我正在尝试创建一个定义项目的类和另一个定义库存的类,其中包含项目的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com