首页 文章

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

提问于
浏览
1

我正在创建一个程序来获取书店库存,每个单独的项目(如ISBN和作者)都在名为Books的结构中 . 由于此清单中将有多本书,我想创建一个Books结构的数组 . 由于我无法控制的外部要求,结构定义必须位于我的类所在的头文件中,并且必须在main()中声明结构数组 .

这是头文件functions.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()中创建结构数组 . 请注意,它允许我从struct 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];
}

When I do this, I get the following compiler error

bookstore.cpp:11:16:错误:非POD元素类型的可变长度数组'Books'图书清单[MAX_SIZE];

为什么在尝试从外部结构声明结构数组时会出现这样的错误,而不是来自同一外部结构的变量?

7 回答

  • 2

    将MAX_SIZE声明为const int,它应该可以工作 . 问题是数组的大小必须在编译时知道(它必须是编译时常量) . 可以在运行时更改int,而const int(或define)则不能 .

  • 0

    C标准不支持可变长度数组 . 如果需要可变长度数组功能,请改用 vector<Books> .

    G允许VLA作为标准C的扩展 . 但是,您不能在C中初始化VLA,也不能在G的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 - Plain Old Data - 类型),因此对于 Books 类型有一个非平凡的构造函数 .

    最简单的解决方法是使用:

    const int MAX_SIZE = 100;
        int size;
        int choice;
    

    或使用:

    std::vector<Books> booklist;
    
  • 0

    在声明结构时,你必须这样给出 .

    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
    
  • 1

    只需转换以下行来定义

    int MAX_SIZE = 100
    

    所以解决方案就是

    #define MAX_SIZE 100
    
  • 0

    如果您不使用typedef,则需要将类型指定为 struct <struct_name>

    int main()
    {
        int MAX_SIZE = 100, size, choice;
        struct Books novels;
        struct Books booklist[MAX_SIZE];
    }
    
  • 1

    下面有一些指示
    一个 . 我认为这是一个错字,头文件必须包含 #endif 语句 .
    湾要在堆栈上创建数组,数组大小必须为 const ,请尝试将 MAX_SIZE 更改为 const int MAX_SIZE = 100 .

  • 0

    关于VLA

    • If your code is C++ (这个问题)

    AFAIK,作为VLA支持, C++ 标准中没有任何内容 . 也许 std::vector 会有所帮助 .

    Solution: 对于此代码,您可以将 int MAX_SIZE = 100 更改为 #define 语句,如 #define MAX_SIZE 100 ,或者将 MAX_SIZE 更改为 const int .


    • If your code is C (如前所述)

    注意:根据您的代码, Books 不是数据类型, struct Books 是 .

    所以,使用以下任何一种:

    • 在您的代码中使用 struct Books

    • 使用 typedef struct Books Books; 然后使用 Books ,就像在代码中使用的一样 .

    此外,就 C 标准而言,VLA是在 C99 标准中引入的 . 您必须通过 --std=c99 提供 gcc 来提升标准 .

相关问题