C++类中的静态数组赋值
C++ assign values to a static array in a Class
- 我是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 不等同于字符串,即使目前它只包含一个字符串。
- 在 Arduino 中为 2D 指针数组赋值
- 我无法为 2D 数组赋值
- 如何在C++中初始化值,然后稍后为uint32_t数组赋值
- 使用 C++ shell 为 C++ 中的 2 D 动态数组赋值,控制台不会打印出任何内容
- 为两个动态数组赋值
- 在类的构造函数中为常量动态大小的数组赋值
- 为结构灵活数组赋值
- 如何在opencv中为三维数组赋值
- 如何从主函数为对象数组赋值
- 数组赋值无法使用指针语法
- C++类中的静态数组赋值
- 多维字符串数组赋值 C++
- 错误:从初始值设定项列表向数组赋值;在ubuntu 1004上工作但在14.04上不工作的代码
- 用于循环数组赋值的C++.正在返回垃圾邮件
- 多维数组赋值
- 无法在c++中为全局数组赋值
- C++程序在为指针的2D数组赋值后崩溃
- 给指针数组赋值
- c++将整型数组赋值给大小相同的空整型数组
- 将数组赋值给派生对象