c++11引入了类型推断定义符 auto和decltype
auto用法如下
auto 变量名 1 = 表达式1,变量名2 = 表达式2,.......;
编译器会根据表达式结果推断出定义的变量的类型,并用表达式值进行初始化
auto忽略表达式的顶层const 和引用的const而指针底层const会保留
先看看前置知识吧
https://www.cnblogs.com/mch5201314/p/11566712.html
https://www.cnblogs.com/mch5201314/p/11485800.html
如果只想定义变量而不让表达式初始化,就用deltype
用法decltype(表达式) 变量 = 表达式
下面弄个例子看看
#include<iostream> using namespace std; int n; double f(int n) { int s = 0; for(int i = 1;i <= n;i++) s += i; return s; } int main() { int i = 10,j,*p = &i,&r = i; const int ic = i,&cj = ic; decltype(f(5)) s;//double s decltype(i + 3.4) x = 9;//double x; decltype(ic + 3) y1;//int y1 decltype(ic) y2 = 4;//const int y2 = 4; //decltype(ic) y3;错误,const int y3 decltype(p) p1;//int *p1; decltype((i)) ri = j;//int &ri = j; decltype(*p) rp = i;//int &rp = i; auto x1 = ic;//int x1 = ic; decltype(cj) x2 = ic;//const int &x2 = ic; return 0; }