从另一个数组值初始化数组大小

sov*_*ova 4 c++ arrays initialization

#include<iostream> 
using namespace std; 

const int vals[] = {0, 1, 2, 3, 4}; 

int newArray[ vals[2] ]; //"error: array bound is not an integer constant"

int main(){
    return vals[2];
}

//returns 2 if erroneous line is removed
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?

Ara*_*raK 10

不幸的是,你不能在标准C++中这样做,因为vals[2]它不是一个常量表达式!在即将推出的标准中,您将constexpr(在g ++ 4.6中实现)轻松地请求编译时评估:

#include<iostream> 
using namespace std; 

constexpr int vals[] = {0, 1, 2, 3, 4}; 

int newArray[ vals[2] ]; // vals[2] is a constant expression now!

int main(){
    return vals[2];
}
Run Code Online (Sandbox Code Playgroud)


gri*_*ett 5

C++编译器只能在编译时分配一个已知大小的数组.如果要分配可变大小的内存,请使用new运算符.

  • 甚至更好,`std :: vector`. (7认同)
  • 对我来说似乎是其他问题的答案 (3认同)

Rom*_*n L 5

const表达式的值有可能在编译时甚至都不知道.例如,您可以使用函数返回的内容初始化常量,例如

const int size = rand(); // random size
Run Code Online (Sandbox Code Playgroud)

所以它不像你想象的那样恒定