作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想用全局变量声明数组的长度。但是我遇到了错误,我对解决这个问题感到困惑。
int BARIS = 8;
//I get error when declare Squares Array with global variable (BARIS variable)
int SquaresInfo[BARIS];
int main(int argc, const char * argv[]) {
cout << "\n\n\n\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Tekan ENTER untuk masuk ke permainan";
if(cin.get() == '\n' ) {
system("clear");
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
gameInterface();
} else {
cout << " ";
}
return 0;
}
声明 SquareInfo 数组的长度时出现错误。我很困惑如何用全局变量声明数组长度
最佳答案
数组的大小应为常量表达式(大于 0)。更改此声明
int BARIS = 8;
到
const int BARIS = 8;
C++ 标准不允许可变长度数组 (VLA),尽管一些编译器有自己的语言扩展,允许使用 VLA。此外,VLA(s) 应具有自动存储期限。也就是说,如果您被允许定义一个 VLA,那么它应该是一个本地数组
来自允许使用 VLA 的 C 标准(6.7.6.2 数组声明符)
- ...If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.
如果变量可能不是常量,则使用 std::vector<int>
而不是数组。例如
#include <vector>
//...
int BARIS = 8;
std::vector<int> SquaresInfo( BARIS );
关于c++ - 如何用全局变量声明全局数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448997/
我是一名优秀的程序员,十分优秀!