今天在学C++中的auto关键字时,在
Linux version 4.10.0-28-generic
Ubuntu 16.04.3
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
环境下编译以下测试程序时会报错
#include<iostream>
#include<vector>
using namespace std;
int main(void)
{
vector<int> v{1,2,3,4,5};
for(auto &i : v)
i *= i;
for(auto i : v)
cout << i << " ";
cout<<endl;
return 0;
}
~
这是个非常简单的程序,肯定不会有什么大问题,但是系统报错了一大堆
/usr/include/c++/5/bits/stl_vector.h:253:7: note: candidate expects 0 arguments, 5 provided
test.cpp:8:14: error: ISO C++ forbids declaration of ‘i’ with no type [-fpermissive]
for(auto &i : v)
^
test.cpp:8:18: warning: range-based ‘for’ loops only available with -std=c++11 or -std=gnu++11
for(auto &i : v)
^
test.cpp:10:13: error: ‘i’ does not name a type
for(auto i : v)
^
test.cpp:12:4: error: expected ‘;’ before ‘cout’
cout<<endl;
^
test.cpp:13:4: error: expected primary-expression before ‘return’
return 0;
^
test.cpp:13:4: error: expected ‘)’ before ‘return’
由于我是刚开始接触C++11的相关知识,所以我刚开始以为是我的g++版本太低(上面是已经升级的版本),所以升级了版本,但是还是一样的,后来经过上网查询来找到我犯的错误是什么,原来如果程序中包含C++11的相关新特性要在编译时加后缀
-std=c++11
所以我g++ test.cpp -std=c++11就编译成功了