C++类中的静态数组赋值

C++ assign values to a static array in a Class

本文关键字:数组 赋值 静态 C++      更新时间:2023-10-16
  • 我是C++新手。编译器抱怨以下行:inv.inventory[0] = "Books"。请帮助我如何分配值到类中的静态数组。

类声明

#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:错误:与清单中的运算符= 不匹配:库存[0] = "书籍" invMain.cpp:7:注意:候选人是:Items&Items::operator=(const Items&)

这里有几点错误:

static Items inventory[5];

static说,所有InventoryItems只有一个inventory.不幸的是,它不会为所有编译器分配空间。OP可能正在看到

未定义对"库存项目::库存"的引用

您可以使用

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

另一个大问题是你试图把方形钉子塞进圆孔里,然后得到一些东西

错误:"运算符="不匹配

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

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

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

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

你也可以像这样调用 do it:

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 中创建二传手函数

void setDesc(string desc)
{
    description = desc;
}

现在,您可以以与operator=大致相同的成本

InventoryItems::inventory[2].setDesc("Beer");

选择它由你决定。我个人喜欢在这种情况下的二传手。你正在做的事情比=更明显,比临时变量更便宜。

你还没有说错误是什么。 我在Visual Studio 2015中编译了相同的代码,并得到了"二进制'=':找不到运算符"。

所以问题是你还没有为 Items 类定义运算符 =。 您需要它,因为 Items 不等同于字符串,即使目前它只包含一个字符串。