2012-11-16 197 views
0

我寫了一個C++程序,其中使用了array對象幷包含<array>頭文件,但是當我嘗試使用g++進行編譯時,它返回了很多錯誤消息,指出「未聲明數組在這個範圍內「。它可能有什麼問題。 計劃是在這裏:數組未在此範圍內聲明

#include <iostream> 
#include <string> 
#include <array> 

using namespace std; 

const int Seasons = 4; 
const array<string, Seasons> Snames = 
{"spring", "summer", "fall", "winter"}; 

void fill(array<double, Seasons>* pa); 
void show(array<double, Seasons> da); 

int main() 
{ 
array<double, Seasons> expenses; 
fill(&expenses); 
show(expenses); 

return 0; 
} 

void fill(array<double, Seasons>* pa) 
{ 
for(int i = 0; i < Seasons; i++) 
{ 
    cout << "Enter " << Snames[i] << " expenses: "; 
    cin >> *pa[i]; 
} 
} 

void show(array<double, Seasons> da) 
{ 
double total = 0.0; 
cout << "\nEXPENSES\n"; 

for(int i = 0; i < Seasons; i++) 
{ 
    cout << Snames[i] << ": $" << da[i] << endl; 
    total += da[i]; 
} 
cout << "Total Expenses: $" << total << endl; 
} 
+0

什麼命名空間?你有沒有在你的代碼中調用它'std :: array'?更好的是,你可以**顯示你的代碼**? – chrisaycock

+0

我不知道!沒人知道。你知道爲什麼?因爲你沒有顯示你的代碼。 – 2012-11-16 22:09:24

+0

你應該發佈你的代碼。 –

回答

6

最可能的原因,爲什麼你的程序不能編譯的是,<array>頭不與預C11編譯器兼容。將

-std=c++0x 

添加到您的g ++的標誌以啓用C++ 11支持。一旦你這樣做,你會得到一個different error,因爲第28行應該是

cin >> (*pa)[i]; 

EDITED;原來的答覆建議缺少參考std::

+0

程序代碼加入 – Sam

+0

@XinHua請參閱編輯。你的程序現在運行([link to ideone](http://ideone.com/TbsHew))。 – dasblinkenlight

1

這就是所謂的std::array - 它與std::命名空間前綴限定符,就像每個標準庫類或函數[template]一樣。

1

添加任何的下方之一的#include之後:

using namespace std; 
using std::array; 
+0

您錯過了此處最重要的修復方案。 – Griwes

+0

你可以請更具體嗎? –

+0

你錯過了寫*爲什麼*這些行解決了問題,'array'是名字空間'std'的成員,這是答案中最重要的部分。又名完全限定名稱爲'std :: array'。 – Griwes