編輯:添加一個默認的構造函數什麼也沒有改變,但增加在: itemlist(0)
初始化劑的庫存構造去除特定誤差。然而,這兩種錯誤的多個實例仍時有發生:使用自定義類與向量:「的std :: vector」的默認構造函數的錯誤
'Item': undeclared identifier
和
'std::vector': 'Item' is not a valid template type argument for parameter '_Ty'
我不知道是否有某種範圍問題的發生在這裏的關於我的兩個獨立的類?
我想創建一個類,它定義了一個Item,另一個類定義了一個Inventory,其中包含一個Items的向量列表。然而,下面的解決方案,我越來越多的錯誤,最顯着的
'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);
}
我有一種感覺它的東西與我的自定義的對象是與我以前做的方式矢量不知何故不兼容試圖使用它們。所有這些都有根本性的錯誤,或者我在某個地方犯了一個簡單的錯誤?
從錯誤消息中可以清楚地看出,要將您的類用作矢量項,您需要提供一個默認的構造函數。如果你不能提供一個存儲在向量中的類的'std :: unique_ptr <>'或'std :: shared_ptr <>'。 –
你最好把shared_ptrs放到vector中而不是對象本身(這會導致大量的複製和克隆) – pm100
這不是問題,但Item.h包含'header.h',它包含'Item .h',並且似乎沒有包含警衛目前...... –