問題描述
我的代碼存在以下問題:
I am having the following issue with my code:
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++ 中,變長數(shù)組是不合法的.G++ 允許將其作為擴展"(因為 C 允許),因此在 G++ 中(無需 -pedantic
關于遵循 C++ 標準),您可以這樣做:
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
如果您想要一個可變長度數(shù)組"(在 C++ 中更好地稱為動態(tài)大小的數(shù)組",因為不允許使用適當?shù)目勺冮L度數(shù)組),您要么必須自己動態(tài)分配內(nèi)存:
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
或者,更好的是,使用標準容器:
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
如果你仍然想要一個合適的數(shù)組,你可以在創(chuàng)建它時使用常量,而不是變量:
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
同樣,如果你想從 C++11 中的函數(shù)中獲取大小,你可以使用 constexpr
:
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
這篇關于Array[n] vs Array[10] - 用變量 vs 實數(shù)初始化數(shù)組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!