【发布时间】: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_back或emplace_back。 -
见this 非常适用的答案。 [tl;dr] 数组大小必须是 compile-time 常量。
-
编译器的诊断是不言自明的。 C++ 中的数组维度必须是常量表达式(在编译时计算)。
const int MaxID = findMaxID();不会导致在编译时调用和评估findMaxID()。它只是防止MaxID在初始化后被更改。要将MaxID用作数组维度,必须使用可在编译时计算的常量表达式对其进行初始化(例如const int MaxID = 10)。