(三)c++11 auto与decltype

从此文章http://c.biancheng.net/view/6984.html参考! 

auto

auto varname = value;  

注意:

  1. auto 不能作为函数参数;
  2. auto 不能作为类的非静态成员变量(static);
  3. auto 不能定义数组
  4. auto 仅是一个占位符不是类型声明;
auto a = 10;
auto *p1 = &a; // 可以和其他类型混合使用
const auto p = a;

decltype

decltype(exp) varname [= value];  

(exp):表达式

varname:变量名

value:赋给变量的值

[]:表示可有可无

int a = 90;
decltype(a) b = 80;
decltype(0.9) c; // 不可以不初始化
c = 8.9;

区别:

auto

[1] 会抛弃引用类型;

[2] 若表达式是非指针,auto会将cv限定符,直接推导成non-const或non-volatile类型

[3] 要求变量必须初始化;

 

decltype

[1] 会保留引用类型;

[2] decltype会保留cv限定符;

[3] 不一定要初始化;

#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    // auto 对非指针或非引用类型,自动将cv限定符抛弃,推倒为non-类型
    // 非指针
    const int a = 9;
    auto  b1 = a;
    b1 = 90;              //将non-const 赋给 const
    cout << b1 << endl;   //通过编译
decltype(a) b2 = a; b2 = 90; // 报错

// 指针 const int * p = &a; auto c1 = p; c1 = 90; // 报错 cout << c1 << endl;
decltype(c1) c2 = c1; c2 = 90; // 报错 // 引用 int x = 8; int & y = x; auto n1 = y; n1 = 20; printf("auto: x=%d, y=%d, n1=%d\n", x, y, n1); decltype(y) n2 = y; n2 = 30; printf("decltype: x=%d, y=%d, n2=%d", x, y, n2); return 0; }

auto: x=8, y=8, n1=20
decltype: x=30, y=30, n2=30

 

posted @ 2020-05-14 18:13  欧阳图图的少年成长记  阅读(116)  评论(0)    收藏  举报