C++ 如何用全局变量声明全局数组的长度?
我想用全局变量声明数组的长度。但我犯了错误,我对解决这个问题感到困惑C++ 如何用全局变量声明全局数组的长度?,c++,arrays,C++,Arrays,我想用全局变量声明数组的长度。但我犯了错误,我对解决这个问题感到困惑 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\
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;
}
intbaris=8;
//使用全局变量(BARIS变量)声明平方数组时出错
int SquaresInfo[BARIS];
int main(int argc,const char*argv[]{
不能只需将数组定义移动到主函数内和/或声明BARIS const您不能拥有可变数组索引,请尝试
#define BARIS 8
int squareInfo[BARIS];
数组的大小应为常量表达式(大于0)。请更改此声明
int BARIS = 8;
到
C++标准不允许可变长度数组(VLA),虽然有些编译器有自己的语言扩展,允许使用VLA(S),而且VLA(s)应该具有自动存储持续时间。也就是说,如果允许定义VLA,则它应该是本地数组< /p>。
来自允许VLA的C标准(6.7.6.2数组声明符)
…如果标识符被声明为具有静态或线程存储持续时间的对象,它不应具有可变长度数组
键入
如果变量可能不是常量,则使用std::vector
代替数组
#include <vector>
//...
int BARIS = 8;
std::vector<int> SquaresInfo( BARIS );
#包括
//...
int-BARIS=8;
标准:向量平方信息(BARIS);
除了其他答案可能会指出c样式数组定义的解决方案(您需要一个可用于在编译时指定数组大小的constepr
),我鼓励使用当前标准建议的方法:
std::array<int,8> SquaresInfo;
std::数组平方信息;
当前大小可以使用其他地方的函数获得
访问某些索引将进行边界检查,并且它还提供更多类似于类型的行为(例如,沿赋值操作自动复制),而不是c样式数组。数组的大小必须是编译时常量。将常量添加到BARIS定义中。@kvorbiev如果您回答不发表评论,我会选择您作为最佳答案(您仍然可以投票支持)或更好的std::array。我当然更喜欢const int BARIS=8
。但是gcc test.cpp将常量int作为索引抛出错误;(g++命令将在没有任何错误的情况下完成)
std::array<int,8> SquaresInfo;