C ++将值赋给Class中的静态数组

时间:2016-02-23 22:59:21

标签: c++ arrays static

  • 我是C ++的新手。编译器抱怨下面的行: inv.inventory [0] =“书籍”。请帮我如何分配值 到类中的静态数组。

//类声明

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class Items
{
private:
    string description;
public:
    Items()
    {
        description = ""; }

    Items(string desc)
    {
        description = desc;}

    string getDescription() { return description; }

};
class InventoryItems {
public:
    static Items inventory[5];

};
// main function
int main()
{
    const int NUM = 3;
    InventoryItems inv;
    inv.inventory[0] = "Books";

    for (int i = 0; i < NUM; i++)
    {
        cout <<  inv.inventory[i].getDescription() << endl;
    }


    return 0;
}

我收到以下错误:

  

invMain.cpp:31:错误:在InventoryItems :: inventory [0] =“Books”中找不到operator =   invMain.cpp:7:注意:候选人是:物品&amp; Items :: operator =(const Items&amp;)

2 个答案:

答案 0 :(得分:1)

你还没有说出错误是什么。我在Visual Studio 2015中编译了相同的代码并获得了“binary'=':找不到运算符”。

所以问题是你还没有为Items类定义operator =。你需要这个,因为Items不等同于string,即使此时它只包含一个字符串。

答案 1 :(得分:1)

这里有一些问题:

static Items inventory[5];

static表示所有inventory只有一个InventoryItems。不幸的是,它并没有为所有编译器分配空间。 OP可能会看到

  

对`InventoryItems :: inventory'的未定义引用

您可以使用

分配存储空间
class InventoryItems {
public:
    static Items inventory[5];

};

Items InventoryItems::inventory[5]; // needs to be defined outside the class

另一个大问题是你试图将方形钉塞在圆孔中并获得某些东西

  

错误:不匹配'operator ='

"Books"const char *,而非项目。 const char *很容易转换为string因为有人花时间编写完成工作的函数。你也必须这样做。

您可以将其转换为项目,然后分配

inv.inventory[0] = Items("Books");

这会创建一个临时Items,然后在复制后会销毁它。有点贵,因为你有一个构造函数和一个析构函数被调用只是为了复制一个dang字符串。

您也可以这样打电话:

InventoryItems::inventory[0] = Items("Books");

因为所有InventoryItems共享相同的inventory,您无需创建InventoryItems来获取inventory

如果您不想创建和销毁额外的对象,可以为带有字符串的Items编写赋值运算符

Items & operator=(string desc)
{
    description = desc;
    return *this;
}

现在两个

InventoryItems::inventory[0] = Items("Books");

InventoryItems::inventory[1] = "Pizza";

的工作。

您还可以在Items

中创建一个setter函数
void setDesc(string desc)
{
    description = desc;
}

现在,您可以获得与operator=

相同的费用
InventoryItems::inventory[2].setDesc("Beer");

你选择它取决于你。我个人喜欢这种情况下的二传手。你所做的比=更明显,而且比临时变量便宜。