我的代码存在以下问题:
int n = 10;
double tenorData[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
返回以下错误:
error: variable-sized object 'tenorData' may not be initialized
而使用 double tenorData[10]
有效。
有人知道为什么吗?
最佳答案
在 C++ 中,可变长度数组是不合法的。 G++ 允许它作为“扩展”(因为 C 允许它),所以在 G++ 中(没有关于遵循 C++ 标准的-pedantic
),你可以这样做:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
如果您想要一个“可变长度数组”(在 C++ 中更好地称为“动态大小的数组”,因为不允许使用适当的可变长度数组),您要么必须自己动态分配内存:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
或者,更好的是,使用标准容器:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
如果你仍然想要一个合适的数组,你可以在创建它时使用一个常量,而不是一个变量:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
同样,如果你想从 C++11 中的函数中获取大小,你可以使用 constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
关于c++ - Array[n] vs Array[10] - 使用变量初始化数组 vs 数值字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15013077/