C ++如何声明一个对象的向量作为类的成员 [英] C++ how to declare a vector of objects as a member of a class

查看:197
本文介绍了C ++如何声明一个对象的向量作为类的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将向量< Item> 声明为另一个类 Inventory 的私有成员,它给我一个错误,说不在范围内。这两个类都在同一个文件中声明。我不知道如何改变它的范围或任何你应该做的,使其工作。

I'm trying to declare a vector<Item> as a private member of another class Inventory, but it is giving me an error saying that Item is not in scope. Both classes are declared in the same file. I don't know how to change the scope that it looks at or whatever you are supposed to do to make it work.

这里的代码,使绝对清楚什么我试图做。

Here is the code to make absolutely clear what I'm trying to do.

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;
};


推荐答案

$ c>必须在作为模板参数使用之前定义。

Item must be defined before its usage as a template argument.

在技术上,你可以在特定上下文中避开前进声明,时间和沮丧,学习确切的规则,更容易确保你先定义它。

Technically, you may be able to get away with a forward declaration in specific contexts, but to save you time and frustration with learning the exact rules, it is easier to just make sure you have defined it first.

一般来说,声明的顺序很重要。如果您在另一种类型的声明中使用某个类型,则必须 定义已使用的类型。该规则的例外涉及指针和引用的使用,其仅需要前向声明。

In general, the order of declarations are important. If you use a type in the declaration of another type, the used type must already be defined. Exceptions to this rule involve usage by pointer and reference which only require forward declaration.

这篇关于C ++如何声明一个对象的向量作为类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆