简体   繁体   English

二维数组中的预期常数

[英]Expected constant in 2d array

double rainPerMonth(const int YEARS)
{
   int monthYear[MONTHS][YEARS];
   // ...
}

Visual Studio shows a squiggly line underneath the array declaration, saying that YEARS must be a constant when I'm creating the array. Visual Studio在数组声明下方显示了一条弯曲的线,表示在创建数组时YEARS必须为常量。 Is this an IDE issue because the variable has yet to be initialized, or am I writing this incorrectly? 这是IDE问题,因为变量尚未初始化,还是我写错了?

MONTHS is already declared globally. MONTHS已在全球宣布。

An array size must be a constant expression - that is, a value known at compile time. 数组大小必须是一个常量表达式-即在编译时已知的值。 (Some compilers offer C-style variable-length arrays as a non-standard extension, but I don't think Visual C++ does. Even if it does, it's better not to rely on such extensions.) (有些编译器提供C样式的可变长度数组作为非标准扩展,但是我不认为Visual C ++可以。即使这样做,也最好不要依赖此类扩展。)

A function argument isn't known at compile time, so can't be used as an array size. 函数参数在编译时未知,因此不能用作数组大小。 Your best option is here is probably 您最好的选择可能是

std::vector<std::array<int, MONTHS>> monthYear(YEARS);

In C++, an array must be sized at compile time. 在C ++中,必须在编译时调整数组的大小。 What you are attempting to do is declare one that is sized at runtime. 您尝试做的是声明一个在运行时调整大小的对象。 In the function you've declared, YEARS is only constant within the scope of the function. 在您声明的函数中, YEARS仅在函数范围内是常量。 You could call it rainPerMonth(someInt); 您可以将其rainPerMonth(someInt); where someInt is the result of some user input (which shows you that the result is not a compile-time constant). 其中someInt是某些用户输入的结果(显示结果不是编译时常量)。

Variable Length Arrays are an extension to C, but not C++. 可变长度数组是C的扩展,但不是C ++的扩展。 To do what you want, you can use dynamic memory, or a std::vector . 要执行所需的操作,可以使用动态内存或std::vector

I think your problem lies in the fact that C++ wants a constant in the sense of compile-time constant to create your variable monthYear . 我认为您的问题在于,C ++希望从编译时常量的monthYear来创建一个变量monthYear If you pass it as a function, it need not be known at compile time? 如果您将其作为函数传递,则在编译时是否不需要知道它? For example: 例如:

const int x=2;
const int y=3;

char xyChoice;
std::cin >> xyChoice;

if (xyChoice == 'x')
rainPerMonth(x);
else
rainPerMonth(y);

I'm unsure, but it seems to me like this would give you a constant int being passed to your function, but the compiler wouldn't know what size to create an array for before runtime? 我不确定,但是在我看来,这将为您提供一个恒定的int传递给您的函数,但是编译器在运行时之前不知道为数组创建什么大小?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM