auto(自动,automatic)是存储类型标识符,表明变量"自动"具有本地范围,块范围的变量声明(如for循环体内的变量声明)默认为auto存储类型。 auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型,类似的关键字还有decltype。举个例子:
int a = 20;
auto au_a = a;
cout << typeid(au_a).name() << endl;
输出:int
分析: 这种用法就类似于JavaScript中的var关键字,auto的自动类型推断发生在编译期;
#includeusing namespace std; int main() { auto greet = []() { cout << "Hello World!"; }; greet(); return 0; }
输出:
Hello World!
再看个栗子
#includeusing namespace std; int main() { auto operation = [] (int a, int b, string op) -> double { if (op == "sum") { return a + b; } else { return (a + b) / 2.0; } }; int num1 = 1; int num2 = 2; auto sum = operation(num1, num2, "sum"); cout << "Sum = " << sum << endl; auto avg = operation(num1, num2, "avg"); cout << "Average = " << avg; return 0; }
输出:
Sum = 3 Average = 1.5



