- 我是 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: error: no match for operator= in InventoryItems::inventory[0] = "Books" invMain.cpp:7: note: candidates are: Items& Items::operator=(const Items&)
最佳答案
这里有一些错误:
static Items inventory[5];
static
表示对于所有 InventoryItems
,只有一个 inventory
。不幸的是,它并没有为所有编译器分配空间。 OP 可能会看到
undefined reference to `InventoryItems::inventory'
你可以分配存储空间
class InventoryItems {
public:
static Items inventory[5];
};
Items InventoryItems::inventory[5]; // needs to be defined outside the class
另一个大问题是你想把方钉塞进圆孔里,然后得到一些东西
error: no match for 'operator='
"Books"
是一个 const char *
,而不是一个 Items。 const char *
很容易转换为 string
,因为有人花时间编写了完成这项工作的函数。您也必须这样做。
你可以把它变成一个Items然后分配给它
inv.inventory[0] = Items("Books");
这会创建一个临时的 Items
,然后在复制后将其销毁。有点贵,因为你有一个构造函数和一个析构函数被调用只是为了复制一个该死的字符串。
你也可以这样调用:
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");
你选择哪个取决于你。我个人喜欢这种情况下的二传手。它比 =
更明显,而且比临时变量更便宜。
关于C++为类中的静态数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589947/