[英]Create a std::vector of std::vectors of class without copy constructor
[英]Using custom class with vectors: 'std::vector' default constructor error
編輯:添加默認構造函數沒有任何改變,但在庫構造函數中添加: itemlist(0)
初始化程序刪除了該特定錯誤。 但是,仍會出現這兩個錯誤的多個實例:
'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 :: vector。 默認構造函數是沒有參數的構造函數,即Item::Item() { ... }
如std::vector<>
s 參考文檔中所述 (強調我的):
T元素的類型。
必須滿足CopyAssignable和CopyConstructible的要求。
對元素施加的要求取決於對容器執行的實際操作。 通常,要求元素類型是完整類型並滿足Erasable的要求,但許多成員函數強加了更嚴格的要求。
所以你仍然需要提供一個拷貝構造函數和賦值運算符。 也Item
需要完全聲明,當vector<Item>
被實例化。
如果無法為您的類提供所需的功能,您可以在vector
存儲智能指針,例如:
std::vector<std::unique_ptr<Item>> itemlist;
要么
std::vector<std::shared_ptr<Item>> itemlist;
這樣做的好處是您不會一直復制Item
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.