【问题标题】:Defining a constant by a variable in C++ [duplicate]在 C++ 中通过变量定义常量 [重复]
【发布时间】:2019-04-07 17:45:20
【问题描述】:

所以我需要通过一个变量来定义一个常量,这样我就可以在数组的定义中使用该值。这行得通吗?

std::fstream scores("scores.txt");
int numberOfLines;
std::string temp;

while (std::getline(scores, temp))
{
    numberOfLines++;
}

const int numberOfLines1 = numberOfLines;
int scoresArr [numberOfLines1] = {};
scores.close();

【问题讨论】:

标签: c++ arrays c++11 variables constants


【解决方案1】:

这行得通吗?

简短回答:不。

长答案。

C 风格的数组需要(在标准 C++ 中)编译时已知的大小。

所以

// ............vvvvvvvvvvvvvv  <-- compile time constant, please
int scoresArr [numberOfLines1] = {};

numberOfLines1 必须知道编译时间。

不幸的是,在您的代码中,numberOfLines1 的值不是已知的编译时间,但它显然未初始化(因此以未定义的值开头)

int numberOfLines;  // <-- initialized with an undefined value

并增加了取决于外部文件的次数,因此必须在运行时增加

while (std::getline(scores, temp))
{
    numberOfLines++;
}

所以:不,不起作用。

【讨论】:

    【解决方案2】:

    你可以使用int *scoresArr = new int[numberOfLines1];

    然后用delete [] scoresArr释放空间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2021-08-30
      • 2011-09-17
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      • 2011-08-27
      相关资源
      最近更新 更多