2014-02-05 47 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',只用一个编译器检查语法。现在答案应该更加正确。 –