0
点赞
收藏
分享

微信扫一扫

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 = #
int& q = num;

decltype(num) x1; //int
decltype((num)) x2; //加内层括号变为引用
decltype((num=num1)) x; //赋值也会变为引用类型

decltype(q + num) x3; //int
decltype(*p) x4; //int &


举报

相关推荐

0 条评论