2014-02-05 51 views
10

我對C++非常陌生,並且在閱讀我的錯誤時遇到了困難我能夠消除其中的大部分錯誤,但是我只能解決一些錯誤,請求幫助。擴展初始化程序列表僅適用於

這裏是程序

#include <string> 
#include <iostream> 
using namespace std; 
int main(){ 
int *bN = new int[9]; 
string bankNum; 
int *number = new int[9]; 
int total, remain; 
int *multi = new int{7,3,9,7,3,9,7,3}; 
cout<<"Please enter the bank number located at the bottom of the check"<<endl; 
cin>>bankNum; 
for(int i = 0; i < 8; i++){ 
    bN[i]= (bankNum[i]-48); 
} 
for(int i = 0; i < 8;i++){ 
    cout<<bN[i]; 
} 
cout<<endl; 
for(int i = 0; i < 8;i++){ 
    cout<<multi[i]; 
} 
cout<<endl; 
for(int i = 0; i < 8;i++){ 
    bN[i] = bN[i] * multi[i]; 
    cout<< bN[i]; 
} 
cout<<endl; 
for(int i = 0; i < 8;i++){ 
    total += bN[i] 
    cout<<total; 
} 
cout<<endl; 
remain = total % 10; 
if(remain == (bankNum[9] - 48)){ 
    cout<<"The Number is valad"<<endl; 
    cout<<remain<<endl; 
} 
} 

和錯誤

[email protected]:~$ c++ bankNum.cpp 
bankNum.cpp: In function âint main()â: 
bankNum.cpp:9:19: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default] 
bankNum.cpp:9:38: error: cannot convert â<brace-enclosed initializer list>â to âintâ in initialization 
bankNum.cpp:30:3: error: expected â;â before âcoutâ 

回答

10

初始化的這種風格,用括號:

int *multi = new int{7,3,9,7,3,9,7,3}; 

被介紹給語言在2011年舊的編譯器不支持它;如果你告訴他們,一些新的(比如你的)只支持它;爲你的編譯:

c++ -std=c++0x bankNum.cpp 

然而,這種形式的初始化仍然是無效與new創建的陣列。由於它很小,只能在本地使用,所以可以聲明一個本地數組;這並不需要C++ 11的支持:

int multi[] = {7,3,9,7,3,9,7,3}; 

這也有固定的內存泄漏的優勢 - 如果你使用new分配內存,那麼你應該delete釋放它,當你與完成它。

如果您確實需要動態分配,你應該使用std::vector分配和釋放你的記憶:

std::vector<int> multi {7,3,9,7,3,9,7,3}; 

當心,你的GCC的版本是很老了,對C++ 11支持不完整。

+0

請看看http://stackoverflow.com/questions/7124899/initializer-list-for-dynamic-arrays –

+0

不完整和錯誤,即使是最新的版本仍然有時會錯過標準的一致性,當你試圖推在C++上更難11新的語言功能...永遠不要相信單個編譯器的結果來說明代碼是否正確形成。 – galop1n

+0

@DieterLücking:夠公平的;我很少直接使用'new',只用一個編譯器檢查語法。現在答案應該更加正確。 –