当结构定义在头文件中时,如何在main()中创建结构数组

How to create an array of structs in main() when struct definition is in a header file?

本文关键字:结构 main 创建 数组 定义 文件      更新时间:2023-10-16

我正在创建一个程序,用于获取书店库存,每个单独的项目(如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=c99gcc来执行标准。