[英]C++ how to declare a vector of objects as a member of a class
我試圖將vector<Item>
聲明為另一個類Inventory
的私有成員,但這給我一個錯誤,指出Item
不在范圍內。 這兩個類都在同一文件中聲明。 我不知道如何更改其外觀的范圍,或者不知道如何使它起作用。
這是完全清楚我要做什么的代碼。
class Inventory {
public:
private:
vector<Item> inventory;
};
class Item {
public:
void SetName(string nm)
{ name = nm; };
void SetQuantity(int qnty)
{ quantity = qnty; };
void SetPrice(int pric)
{ price = pric; };
virtual void Print()
{ cout << name << " " << quantity << " for $" << price
<< endl; };
virtual ~Item()
{ return; };
protected:
string name;
int quantity;
int price;
};
必須在將Item
用作模板參數之前對其進行定義。
從技術上講,您也許可以在特定情況下放棄前向聲明,但是為了節省時間和學習確切的規則而感到沮喪,僅需先定義就容易了。
通常,聲明的順序很重要。 如果在其他類型的聲明中使用一個類型,則必須已經定義了使用的類型。 該規則的例外情況涉及指針和引用的使用,它們僅需要向前聲明。
由於std::vector<Item>
本身就是一種類型,因此必須在Item
類的聲明之后進行聲明 。
(這是類似的規則class Child : public Base
,申報Base
需要出現上面那條線)。
向前聲明 並不足夠。
解決這個問題的一種方法是使用std::vector<std::shared<Item>>
(智能指針的向量),但是當然會改變向量的結構。 在那種情況下,向前聲明就足夠了。
首先定義物料,然后定義庫存。
class Item {
public:
void SetName(string nm)
{ name = nm; };
void SetQuantity(int qnty)
{ quantity = qnty; };
void SetPrice(int pric)
{ price = pric; };
virtual void Print()
{ cout << name << " " << quantity << " for $" << price
<< endl; };
virtual ~Item()
{ return; };
protected:
string name;
int quantity;
int price;
};
class Inventory {
public:
private:
vector<Item> inventory;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.