C++如何将对象的向量声明为类的成员

C++ how to declare a vector of objects as a member of a class

本文关键字:声明 成员 向量 C++ 对象      更新时间:2023-10-16

我正在尝试将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 BaseBase的声明需要出现在该行上方)。

仅仅向前申报是不够的

一种方法是使用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;
};