C++ primer:第二章备忘。

来源:互联网 发布:软件产品出口退税政策 编辑:程序博客网 时间:2024/06/05 07:05

1、C++算术类型
分四种:
布尔类型:bool
char型:char wchar_t char16_t char32_t
整型:short int long long long
浮点型:float double long double

其中整型都是带符号的,char是否带符号不确定,视机器而定

2、顶层const和底层const
顶层const:(标识符)对象本身是个常量
底层const:与指针和引用等符合类型的基本类型部分有关

int i=0;
int *const p1=&i; //p1值不可更改,顶层const
const int ci=42; //ci值不可修改,顶层const
const int *p2=&ci; //p2值可以更改,底层const
const int &r=ci; //用于声明引用的const都是底层const
(1)顶层const不可被赋值,因为顶层const本身含义就是对象本身是个常量!
所以像上述p1、ci是不可被赋值的

。。写到一半看了下知乎,其实顶层const和底层const实为译者翻译的问题。
具体请见:https://www.zhihu.com/question/24785843
看懂了根本不用在意是什么const。

3、constexpr和常量表达式
常量表达式:值不会改变并且在编译过程就可以得到计算结果的表达式。。。
constexpr类型就是用来验证变量的值是否为常量表达式。

const int *p=nullptr;
constexpr int *p=nullptr;
//等同于 int *const p=nullptr;但又不完全等同。首先constexpr要求在编译期间就检查p所指向的值是否已经确定!

例:
在main函数中
{
const int i=0;
int u=0;
constexpr const int *iii=&i; //&i must have a constant value
constexpr int *uuu=&u; //&u must have a constant value
}
因为i和u只有在main函数执行时候才有确定的存放位置,所以编译期间并不能确定&i和&u的值

如果换成:
全局变量:
const int i=0;
int u=0;
在main函数中
{
constexpr const int *iii=&i;
constexpr int *uuu=&u;
}
则编译通过。

4、auto类型说明符
(1)auto定义的变量必须有初始值。
(2)auto一般会忽略掉顶层const(因为赋值是拷贝副本)
int i=0;
const int ci=i;
const int &cr=ci;
auto b=ci; //int b. ci的顶层const特性被忽略掉了
auto c=cr; //int c.cr是ci的别名,ci本身是一个顶层const
auto d=&i; //int* d
auto e=&ci; //const int* e;&ci对常量对象取地址 为底层const,保留

(3)设置一个类型为auto的引用时,初始值中的顶层常量属性仍然保留
auto &g = ci; //const int& g
auto &h=42; // initial value of reference to non-const must be an lvalue (非常量引用)
const auto &j =42; //可以为 常量引用 绑定字面值

5、decltype
希望从表达式的类型推断出要定义的变量的类型,但是不想用该表达式的值初始化变量

decltype(表达式)
(1)如果表达式是一个变量
返回该变量的类型(包括顶层const和引用在内)

(2)若表达式不是变量,则返回表达式结果对应的类型

(3)表达式的内容是解引用操作,则得到引用类型

(4)若给变量加一层括号,会被当成一个表达式,得到引用类型
decltype(p)=>int
decltype((p))=>int &