c++ 之 引用类型 const 用法

引用即别名

引用必须初始化因为其是常量

引用是常量 不能定义引用的引用

只能绑定常量,不能和常量(字面值)及表达式绑定

 

const定义之后就不能更改,所以定义时就要初始化

int i;

const int j = i;  //合法

默认 const 的值只在文件内有效

对于const变量定义和声明都使用extern修饰

 

const的引用:

  可以绑定到const对象上,像绑定到其他对象上一样又叫对常量的引用(reference to const)

      const int ci = 1234;

  const int &r1 = ci;

 初始化常量引用时可以用任意表达式(结果得同类型)作为初始值

  int i = 42;

  const int &r1 = i;

  const int &r2 = 42;

  const int &r3 = r1 * 2;

 

顶层const表示指针本身是个常量,底层const表示指针所指的duixiang

是个常量.

  如:  const int a = 4;

     const int *p = &a;   //底层const指针

     int * const p1 = &a;  //顶层const指针

 

constexpr变量:

  c++11新标准规定,允许变量声明为constexpr类型以便由编译器

  来验证变量的值是否是一个常量表达式.

声明为constexpr的变量一定是一个常量,而且必须用常量表达式初始化:
    constexpr int mf = 20

    constexpr int limit = mf + 1;

 

指针和引用都能定义成constexpr,但它们的初始值是严格限制的

一个constexpr指针的初始值必须是nullptr或0,或是存储于某个固定

地址中的对象.

 

  const int *p = nullptr;    //p是一个指向整型常量的指针

  constexpr int *q = nullptr;  //p是一个指向整数的常量指针

 

类型别名: 定义别名可用typedef和using两个命令

  1. typedef double wages; typedef wages base, *p;

  2. using SI = Sales_item;  //SI是Sale_item的同义词

 

auto:  auto ordinarily ignores top-level const

  auto a = b + c;

  const int ci = i;

  const auto f = ci;

  auto &g = ci;

  const auto &j = 42;

decltype:  When the expression to which we apply decltype is a variable,

decltype returns the type of that variable, including top-level const and
references:

  decltype(f())  sum = x;  //sum has whatever type f returns

  const int ci = 0, &cj = ci;

  decltype(ci) x = 0; // x has type const int
  decltype(cj) y = x; // y has type const int& and is bound to x
  decltype(cj) z; // error: z is a reference and must be initialized

 

// decltype of a parenthesized variable is always a reference
  decltype((i)) d; // error: d is int& and must be initialized
  decltype(i) e; // ok: e is an (uninitialized) int

 

转载于:https://www.cnblogs.com/oh-mine/p/5517829.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值