当结构定义在头文件中时,如何在main()中创建结构数组
How to create an array of structs in main() when struct definition is in a header file?
我正在创建一个程序,用于获取书店库存,每个单独的项目(如ISBN和作者)都在一个名为Books的结构中。由于这个清单中会有多本书,所以我想创建一个books结构的数组。由于我无法控制的外部需求,结构定义必须在类所在的头文件中,并且结构数组必须在main()中声明。
这是头文件函数中的结构定义。h:
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include <iostream>
#include <string>
using namespace std;
struct Books
{
int ISBN;
string Author;
string Publisher;
int Quantity;
double Price;
};
现在我尝试在main()中创建结构数组。请注意,它允许我从结构体Books创建一个变量,但不能创建数组:
#include <iostream>
#include <string>
#include <fstream>
#include "functions.h"
using namespace std;
int main()
{
int MAX_SIZE = 100, size, choice;
functions bookstore;
Books novels;
Books booklist[MAX_SIZE];
}
执行此操作时,会出现以下编译器错误
bookstore.cpp:1:1:16:错误:非POD元素的可变长度数组键入"书籍"图书书目[MAX_SIZE]
为什么我在试图从外部结构中声明结构数组时会出现这样的错误,而不是从同一外部结构中宣布变量?
C++标准不支持可变长度数组。如果需要可变长度数组功能,请改用vector<Books>
。
G++允许VLA作为标准C++的扩展。然而,您不能在C中初始化VLA,也不能在C++的C++方言中初始化。因此,VLA的元素不能有(非平凡的)构造函数。错误信息告诉你:
variable length array of non-POD element type 'Books' Books booklist[MAX_SIZE];
您有一个VLA,因为MAX_SIZE
不是const int MAX_SIZE = 100
。您不能创建类型为Books
的VLA,因为string
成员具有构造函数(不是POD——普通旧数据——类型),因此Books
类型有一个非平凡的构造函数。
最简单的修复方法是使用:
const int MAX_SIZE = 100;
int size;
int choice;
或者使用:
std::vector<Books> booklist;
将MAX_SIZE声明为常量int,它应该可以工作。问题是数组的大小必须在编译时已知(它必须是一个编译时常数)。int可以在运行时更改,而const int(或define)不能更改。
在声明必须像这样给出的结构时。
struct Books booklist[MAX_SIZE];
或者在headerfile
中创建typedef。
typedef struct Books
{
int ISBN;
string Author;
string Publisher;
int Quantity;
double Price;
}Books;
使MAX_SIZE
的值如下。
#define MAX_SIZE 100
只需转换以下行即可定义
int MAX_SIZE = 100
所以解决方案是
#define MAX_SIZE 100
如果不使用typedef,则需要将类型指定为struct <struct_name>
int main()
{
int MAX_SIZE = 100, size, choice;
struct Books novels;
struct Books booklist[MAX_SIZE];
}
下面的一些指针
a.我认为这是一个拼写错误,头文件必须包含#endif
语句
b.要在堆栈上创建数组,数组大小必须为const
,请尝试将MAX_SIZE
更改为const int MAX_SIZE = 100
。
关于VLA:
-
如果您的代码是
C++
(此问题)
AFAIK,C++
标准中没有任何内容支持VLA。也许std::vector
会有所帮助。
解决方案:对于此代码,您可以将int MAX_SIZE = 100
更改为#define
语句,如#define MAX_SIZE 100
或使MAX_SIZE
的类型为const int
。
-
如果您的代码是
C
(如前所述)
注意:根据您的代码,Books
不是数据类型,struct Books
是.
因此,使用以下任一项:
- 在代码中使用
struct Books
- 使用
typedef struct Books Books;
,然后使用代码中使用的Books
另外,就C
标准而言,在C99
标准中引入了VLA。您必须通过提供--std=c99
和gcc
来执行标准。
- 如何循环打印顶点结构
- 通过方法访问结构
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- QT C++,从子层次结构调用 main 中的函数
- 如何修复结构播放器对象中的矢量位置,以便它在 Main 中与 me.position 一起使用?
- 地图数据结构在 Main 中不显示保存的条目.cpp
- 在声明末尾或 main 中声明结构或类实例之间的区别
- Visual Studio可维护性索引的层次结构仅向下到main()
- 在 main 之外的函数中使用结构
- 当结构定义在头文件中时,如何在main()中创建结构数组
- C++:在main.cpp中声明一个结构,但在头中有一个带类的模板的任何可能性
- 指向其他结构的master结构-如何使用main之外的值
- 面向C++的main.cpp中的可视化结构声明问题
- 使用 getline 和层次结构时"invalid use of ‘struct main()"
- 如何在 main 之外的类中使用结构函数
- pthread:我想将 main 中的结构指针传递给 pthread 调用的函数
- 在自己的.cpp中定义一个结构,然后在main中使用它
- 如何在C++中将链表结构返回到main
- 从c++中的main调用类中的结构体
- 体系结构的未定义符号x86_64:"_glutInit",引用自:_main in main.o / Netbeans on Mac