c++11中添加了自动推导变量的类型auto,以及decltype表示函数的返回值。
auto
auto可以像别的语言一样自动推导出变量的实际类型。
在实际中,auto像是一个”占位符“,使用auto声明的变量必须要进行初始化,以让编译器推导出它的实际类型,在编译时将auto换成真正的类型。
语法:实际使用例子:- #include <iostream>
- using namespace std;
- int main() {
- //没有const修饰
- auto x = 3.14; //double
- auto y = 520; //int
- auto z = 'a'; //char
- //auto nb; //语法错误
- //auto double nbl; //语法错误
- int temp = 110;
- auto* a = &temp; //&temp:int* auto*:int* auto:int
- auto b = &temp; //auto:int*
- auto& c = temp; //auto:int
- auto d = temp; //auto:int
- //有const修饰
- int tmp = 250;
- const auto a1 = tmp; //auto:int a1:const int
- auto a2 = a1; //a1不是指针也不是引用 auto:int a2:int
- const auto& a3 = tmp; //a3:const int& auto:int
- auto& a4 = a3; //a3是引用类型 a3:const int& a4:const int& auto&:const int& auto:const int
- auto* pt4 = &a1; //&a1是地址 a1:const int pt4:const int* auto:const int
- system("pause");
- return 0;
- }
复制代码 需要注意的是:
在auto和指针、引用结合在一起时,推导的结果会保留const、volatile关键字(volatile表示变量,经常修改的变量)
- 当变量不是指针或者引用类型时,推导的结果中不会保留const、volatile关键字。
- 当变量时指针或者引用类型时,推导的结果中会保留const、volatile关键字。
就如上述代码中的 //有const修饰 后面的代码,需要注意变量是否为指针或者引用类型。
auto不能推导的4个情况
1. 不能作为函数参数使用,因为只有在函数调用的时候才会给函数参数传递实参,auto要求必须要给修饰的变量赋值,因此二者不矛盾。
[code]int func(auto a, auto b) { //error cout |