2015-10-13 44 views
1

編輯:添加一個默認的構造函數什麼也沒有改變,但增加在: 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); 
} 

我有一種感覺它的東西與我的自定義的對象是與我以前做的方式矢量不知何故不兼容試圖使用它們。所有這些都有根本性的錯誤,或者我在某個地方犯了一個簡單的錯誤?

+2

從錯誤消息中可以清楚地看出,要將您的類用作矢量項,您需要提供一個默認的構造函數。如果你不能提供一個存儲在向量中的類的'std :: unique_ptr <>'或'std :: shared_ptr <>'。 –

+0

你最好把shared_ptrs放到vector中而不是對象本身(這會導致大量的複製和克隆) – pm100

+1

這不是問題,但Item.h包含'header.h',它包含'Item .h',並且似乎沒有包含警衛目前...... –

回答

3

你需要有一個默認的構造函數使用std :: vector的。默認的構造是一個沒有參數,即,Item::Item() { ... }

+0

我已經添加了一個默認的構造函數和它的原型: 'Item(); Item(std :: string n,std :: string d,int c);' ...和... 'Item :: Item(){} Item :: Item(string n,string d, int c) { \t name = n;}' 但是仍然出現同樣的錯誤。如果我還向庫存構造函數中添加了一個初始化項,如下所示: 'Inventory :: Inventory():itemlist(0) { }' 這個特定的錯誤消失了,但我仍然在整個' Item':未聲明的標識符'和''std :: vector':'Item'不是參數'_Ty''的有效模板類型參數 - 是否存在某種範圍問題? – JosephParkins

+0

@JosephParkins你在包含文件中有循環依賴,正如R.Kapp指出的那樣。 – haavee

+1

如果已經提供了另一個(非默認)構造函數,編譯器將不會生成默認構造函數。如果沒有提供構造函數,則默認構造函數僅由編譯器創建。 –

0

std::vector<>小號reference documentation(重點煤礦)中提到:

Ť類型元件。
必須滿足CopyAssignable和拷貝構造的要求。
所上的元素強加的要求取決於容器進行的實際操作。一般情況下,就要求元素類型是一個完整的類型,滿足可擦寫的要求,但許多成員函數施加更嚴格的要求。

所以你仍然需要提供一個拷貝構造函數和賦值操作符。當vector<Item>被實例化時,還需要完全聲明Item


您可以在vector智能指針存儲但是,如果它不能夠爲你的類提供所需的功能,例如:

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

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

這具有的優點是您沒有隨時複製您的實例Item

相關問題