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

时间:2014-11-21 16:32:15

标签: c++

我试图将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;
};

3 个答案:

答案 0 :(得分:3)

Item必须在用作模板参数之前定义。

从技术上讲,你可以在特定的环境中逃避前瞻声明,但为了节省你学习确切规则的时间和挫折感,更容易确保你首先定义它。

一般而言,声明的顺序很重要。如果在另一种类型的声明中使用类型,则必须定义已经使用的类型。此规则的例外情况涉及指针和引用的使用,只需要前向声明。

答案 1 :(得分:2)

由于std::vector<Item>本身就是一种类型,因此必须在Item类的声明之后声明。

(它类似于class Child : public Base的规则,Base的声明需要出现在该行的上方。

转发声明 不足。

这方面的一种方法是使用std::vector<std::shared<Item>>(智能指针向量),但这当然会改变向量的结构。在这种情况下,前向声明 就足够了。

答案 2 :(得分:1)

首先定义项目,然后定义库存。

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;
};
相关问题