c++ - 结构中的结构数组,C++ 代码

标签 c++ structure

我正在为最终成为 MUD 的东西准备一些代码;这是我的第一个“大”项目,我正在逐步纠正错误;然而,现在有些问题阻碍了我的项目,我似乎无法打破它们。这是我的代码:

#include <iostream>
using namespace std;

int test_var;
#define K    125
#define TEST 50

struct item {
int quantity;
//Some More Stuff Will Be Inside Later//
};

struct inventory {
  struct item[K];  //Error 1 - "expected unqualified-id before '[' token"
} test;

int main()
{
cout << "Number?" << endl;
cin >> test_var;
test.item[TEST].quantity = test_var;  //Error 2 - "'struct inventory' has no member named 'item'"
cout << test.item[TEST].quantity << endl;  //Error 3 - "'struct inventory' has no member named 'item'"
cout << test.item[TEST].quantity;  //Error 4 - "'struct inventory' has no member named 'item'"
return 0;
}

我不得不道歉,因为这段代码有点草率,但这代表了我试图完成的两件事。第一,我需要某种方法在结构“库存”中包含一组结构“项目”。第二,我需要确保我可以访问结构中的各个元素;实际代码涉及结构内部的更多结构,我可以访问单个非结构元素(整数、 bool 值、 double 值、字符串)至关重要。如果有人可以就这些问题提供许多建议,我将不胜感激。谢谢

最佳答案

struct item[K];

您缺少结构对象的标识符/名称。请注意,item 本身是一个结构。所以,试试

struct item obj[K];  // struct key word is unnecessary

关于c++ - 结构中的结构数组,C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111792/

相关文章:

java - 字母表的每个排列最多 29 个字符?

c++ - 结构的动态数组

C - 字节数组到结构(dns 查询)

c - 将文件中的整数数组存储在结构 C 中

java - 如何在链表java中的第一个元素前面添加一个点?

c++ - 在 OpenCV 的 namedWindow 之前或之后初始化 Tesseract

c++ - 奇怪的 VC++ 编译错误,C2244

c++ - 如何使用堆栈C++以相反的顺序读取文件和打印

c# - 为什么要在 C# 中再次分配数组中的每个元素

Python - 更改 JSON 值和 pretty-print