Array [n] vs Array [10] - 初始化具有變量與實數(shù)的數(shù)組我的代碼出現(xiàn)以下問題: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]作品。誰知道為什么?
2 回答

海綿寶寶撒
TA貢獻(xiàn)1809條經(jīng)驗 獲得超8個贊
在C ++中,可變長度數(shù)組是不合法的。G ++允許將其作為“擴(kuò)展”(因為C允許),因此在G ++中(不-pedantic
遵循C ++標(biāo)準(zhǔn)),您可以:
int n = 10;double a[n]; // Legal in g++ (with extensions), illegal in proper C++
如果你想要一個“可變長度數(shù)組”(在C ++中更好地稱為“動態(tài)大小的數(shù)組”,因為不允許使用適當(dāng)?shù)目勺冮L度數(shù)組),你必須自己動態(tài)分配內(nèi)存:
int n = 10;double* a = new double[n]; // Don't forget to delete [] a; when you're done!
或者,更好的是,使用標(biāo)準(zhǔn)容器:
int n = 10;std::vector<double> a(n); // Don't forget to #include <vector>
如果你仍然需要一個合適的數(shù)組,你可以在創(chuàng)建它時使用常量而不是變量:
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
:
constexpr int n(){ return 10;}double a[n()]; // n() is a compile time constant expression
添加回答
舉報
0/150
提交
取消