auto定义的变量 对初始化的值进行类型推导
int main()
{
auto x = 10;
auto dx = 12.23;
auto ch = 'a';
}
int main()
{
auto x = 5;//x int
const auto *xp = &x;//xp const int*;auto const int
auto ip = &x;//ip int*;auto int
auto *sp = &x;//sp int*;auto int
return 0;
}
auto并不能代表一个实际的类型声明 ,只是一个类型的占位符
使用auto声明的变量必须具有初始值,以让编译器推演出它的实际类型,并在编译的时候将auto定位符替换为真正的数据类型
auto和指针引用结合的时候,可以带上cv限定符
int main()
{
const int a = 10;
auto*p= &a;//p const int * ,auto const int
return 0;
}
int main()
{
const int a = 10;
auto b = a;//b=int auto int
auto&c = a;//c const int & ,auto const int
return 0;
}
void func(auto x)
{
cout << "x type:" << typeid(x).name() << endl;
cout << x << endl;
}
int main()
{
func(12);
func(12.23);
func('a');
const int x = 10;
func(&x);
return 0;
}
auto作为函数的形参类型
void func(auto x)//首地址
{
cout << sizeof(x) << endl;
cout << typeid(x).name() << endl;
}
void funr(auto &x)//整个数组
{
cout << sizeof(x) << endl;
cout << typeid(x).name() << endl;
}
int main()
{
int ar[10] = { 1,2,3 };
func(ar);
funr(ar);
return 0;
}
1.C11中auto成为类型指示符
2.auto不能用于函数参数
3.auto不能用于非静态成员函数
4.auto无法定义数组
5.实例化模板时不能使用auto作为模板参数
C++11新增了decltype关键字用来编译时推演一个表达式的类型
语法格式
decltype(exp)其中exp表示一个表达式(expression)
int main()
{
int x = 10;
decltype(x)y = 1;//y=int
decltype(x+y)z = 10;//z=int
double dx = 10;
decltype(x + dx)c;
const int&a=10;
decltype(a)b=10;//常引用类型
//连同const属性也能进行推演
return 0;
}
decltype与auto都可以用来推演
auto所修饰的变量必须被初始化,编译器需要通过初始化来确定auto所代表的的类型,即必须定义变量
decltype编译器在编译的时候并不会去计算括号内表达式的值有多层括号返回为引用