C++如何将对象的向量声明为类的成员
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;
};
相关文章:
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- 如何使用模板声明成员函数?(不是模板类)
- 如何使用 Boost.Hana 声明成员变量
- 声明成员对象而不调用其默认构造函数
- 使用函数类型语法声明成员函数
- 尝试访问标头声明成员时出现隔离错误
- 根据二手构造函数声明成员
- C 模板明确声明成员函数值/避免了宏的问题
- 如何在基本模板类中声明成员,其中类型取决于派生类的类型
- 错误:类中没有声明成员函数
- 我可以使用相同的名称为周围作用域中的类型声明成员类型别名吗
- 从variadic模板参数声明成员变量
- 在类(C )中使用模板时未声明成员函数
- 错误:类中未声明 '' 成员函数
- 如何在指向常量地址时声明成员函数常量指针
- 何时以及为什么在堆C++上声明成员变量
- C++ 错误:未在范围内声明;成员函数
- 在不声明成员变量的情况下更改按钮颜色
- 错误 C2535:已定义或声明成员函数
- 当声明成员函数时,*New()是什么意思