C++中auto关键字的使用及编译错误解决


auto可以自动帮我们推断变量的类型
比如在定义一些难以确定的变量类型时
 35     func_log(__func__, "");
 36     // vector<Student>::iterator it = Students.begin();
 37     for (auto it = Students.begin(); it != Students.end(); it++)
 38     {
 39         if (id == it->id)
 40         {
 41             cout << "remove: " << id << endl;
 42             Students.erase(it);
 43             break;
 44         }
 45     }
 
但是如果直接使用g++命令编译会报错
大概如下

vector.cpp: In function ‘void remove(int)’:
vector.cpp:37:12: error: ‘it’ does not name a type
vector.cpp:37:35: error: expected ‘;’ before ‘it’
vector.cpp:37:35: error: ‘it’ was not declared in this scope

默认把auto当作声明自动声明周期的关键字(C++98标准),而不是自动类型的关键字;
在C++11标准中auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型

因此如果要解决此问题需要在编译时添加-std=c++11的编译选项;
g++ -std=c++11 vector.cpp -o vector
 

猜你喜欢

转载自blog.csdn.net/halazi100/article/details/84037429