C++新的类型说明符

基于C++ primer第二章的总结

const限定符

  • 顶层const : 指针本身是个常量

    • int* const 指针的指向不能改变 值可以改变
  • 底层const : 指针所指向的对象是个常量

    • const int* 指针的值不能改变 指针的指向可以改变

constexpr和常量表达式

​ 由编译器来验证它所修饰的变量是否是一个常量表达式

  • 声明为constexpr 的变量一定是一个常量

  • constexpr指针的初始值必须是nullptr或者是0,或者是存储与某个固定地址的对象(全局变量或static静态变量

  #include <iostream>
  using namespace std;
  extern int a;
  int b = 100;
  
  int main()
  {
  	static int w = 10;
  	constexpr int* q = nullptr;
  	constexpr int* p = &w;	//静态变量
      constexpr int* p = &b;	//全局变量
  	*p = 99;
  
  	return 0;
  }
  • constexpr函数
    • 函数的类型和形参必须都是字面值类型
    • 必须只有一条return语句
    • 通常constexpr函数和inline函数放在头文件中
    constexpr int new_sz()
    {
    	return 42;
    }
    constexpr size_t scale(size_t cbt)
    {
    	//返回常量表达式
    	return new_sz*cnt;
    }
    
    

类型别名

  • typedef

    typedef double My_Dou;
    typedef My_Dou My_DouDou;
    
  • using

    using My_int = int;
    using My_int_int = My_int;
    
  • 当某个类型别名是复合类型时,千万不要将其按部就班拆开读

    #include <iostream>
    using namespace std;
    
    typedef char* My_pstr;
    
    int main()
    {
    	
    	const My_pstr* str = nullptr;
        //正确理解: 指向char的常量指针
    	const My_pstr str = nullptr;
        
        //错误理解: 指向const char的指针
    	const char* str = nullptr;	
    
    	return 0;
    }
    

auto类型说明符

  • 自动推断类型 必须要有初始值

  • 若非const auto声明 则auto默认忽略顶层const的作用 保留底层const

    #include <iostream>
    using namespace std;
    int main()
    {
    	//auto
    	const int a = 5;
    
    	//忽略a的顶层const的特性
    	auto num1 = a;			//相当于 int
    	//保持a的顶层const特性
    	const auto num2 = a;	//相当于const int
    
    	//auto& x = 42; 错误 不能为非常量引用绑定字面值
    	//可以为常量引用绑定字面值
    	const auto& x = 42;
    
    	const int i = 42;
    	auto j = i;				// int
    	const auto& k = i;		// const int&
    	const auto &k2 = i;		// const int&
    	auto* p = &i;			// const int*
    	const auto* p1 = &i;	// const int* 
    	const auto j2 = i;		// const int
    
    	return 0;
    }
    

decltype指示符

  • 选择并且返回操作数的数据类型 但是并不计算表达式的值,只是推断出其类型

    	const int j = 10;
    	const int& cj = j;
    
    	decltype(j) a = 0;	// a:const int
    	decltype(cj) b = a;	// b: const int&
    	//decltype(cj) c;	引用必须初始化
    
    	int num = 5;
    	int* p = &num;
    	int& q = num;
    	
    	decltype(num)	  x1;	//int
    	decltype((num))   x2;	//加内层括号变为引用
    	decltype((num=num1)) x;	//赋值也会变为引用类型
    
    	decltype(q + num) x3;	//int
    	decltype(*p)	  x4;	//int &
    
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yuleo_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值