【问题标题】:Defining array bound with const int does not work定义用 const int 绑定的数组不起作用
【发布时间】:2020-09-22 05:00:44
【问题描述】:

我想根据文本文件中有多少行来初始化一个数组,以便我可以将文本数据读入程序,但我遇到了结构问题。到目前为止,我知道我需要用一个常量定义数组边界,我已经尝试过这样做,但是我收到错误说我没有用 integral constant-expression 定义,尽管我相信这就是我正在做的事情。

我正在使用 g++ 按照 C++17 标准编译我的代码。下面我只包含了相关代码。

//tools.h

int findMaxID()
{
    std::ifstream fin("\data\items.txt");
    char ch;
    int z = 1;
    while(fin)
    {
        fin.get(ch);
        if(ch == '\n')
            z++;
    }
    return z;
}
const int MaxID = findMaxID();

// data.h

#include"tools.h"

struct ItemData
{
    public:
        unsigned int ID[::MaxID];
        char Name[::MaxID][32];
        char Type[::MaxID][8]; 
};
data.h:15:21: error: size of array 'ID' is not an integral constant-expression
   15 |   unsigned int ID[::MaxID];
      |                   ~~^~~~~
data.h:16:15: error: size of array 'Name' is not an integral constant-expression
   16 |   char Name[::MaxID][32];
      |             ~~^~~~~
data.h:17:15: error: size of array 'Type' is not an integral constant-expression
   17 |   char Type[::MaxID][8];

我不知道该怎么做。我已经尝试了所有的东西,我尝试使用向量而不是数组,但是在使用多维时我发现它很尴尬和令人困惑,我尝试使用指向该值的指针。也许我设置错了。我所知道的是,我已经尽了最大的努力来克服这个问题,但这个问题似乎不是我能解决的。希望您能帮我解决这个问题。

【问题讨论】:

  • 这在编译时无法确定,因此无法在这样的数组中使用。在 C++ 中,使用std::vector 表示数组,使用std::string 而不是字符数组。
  • 他们有什么“尴尬和困惑”?如果提前适当调整大小,或者如果被扩展,那么它们在使用中与 C 数组相同,那么您需要根据需要使用 push_backemplace_back
  • this 非常适用的答案。 [tl;dr] 数组大小必须是 compile-time 常量。
  • 编译器的诊断是不言自明的。 C++ 中的数组维度必须是常量表达式(在编译时计算)。 const int MaxID = findMaxID(); 不会导致在编译时调用和评估 findMaxID()。它只是防止 MaxID 在初始化后被更改。要将MaxID 用作数组维度,必须使用可在编译时计算的常量表达式对其进行初始化(例如const int MaxID = 10)。

标签: c++ c++17


【解决方案1】:

在设计数据结构时,首先尝试考虑单一情况:

struct ItemData
{
    public:
        unsigned int ID;
        std::string Name;
        std::string Type; 
};

然后分别处理这些结构:

std::vector<ItemData> items;

您可以使用emplace_back 通过读取数据并对其进行解析来轻松地添加条目。

【讨论】:

    【解决方案2】:

    数组大小必须是编译时常量。

    在这种情况下,您的 size 变量在运行时取值,而这标准禁止

    要解决此问题,请尝试使用 c++ 实用程序,例如 std::string 用于 char 数组,std::vector 用于其他类型数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2022-01-23
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多