Contents

顶层const和底层const

顶层const和底层const const_cast

区分

一个指针本身添加const限定符就是顶层const,而指针所指的对象添加const限定符就是底层const。

1
2
3
4
5
6
7
int num_a = 1;
int const  *p_a = &num_a; //底层const
//*p_a = 2;  //错误,指向“常量”的指针不能改变所指的对象

int num_b = 2;
int *const p_b = &num_b; //顶层const
//p_b = &num_a;  //错误,常量指针不能改变存储的地址值

作用

  • 执行对象拷贝时有限制,常量的底层const不能赋值给非常量的底层const
1
2
3
4
int num_c = 3;
const int *p_c = &num_c;  //p_c为底层const的指针
//int *p_d = p_c;  //错误,不能将底层const指针赋值给非底层const指针
const int *p_d = p_c; //正确,可以将底层const指针复制给底层const指针
  • 使用命名的强制类型转换函数const_cast时,需要能够分辨底层const和顶层const,因为const_cast只能改变运算对象的底层const。
1
2
3
4
5
6
nt num_e = 4;
const int *p_e = &num_e;
//*p_e = 5;  //错误,不能改变底层const指针指向的内容
int *p_f = const_cast<int *>(p_e);  //正确,const_cast可以改变运算对象的底层const。但是使用时一定要知道num_e不是const的类型
*p_f = 5;  //正确,非顶层const指针可以改变指向的内容
cout << num_e;  //输出5
  • 底层const可形成重载 顶层const不形成重载。 底层const和非const都可匹配底层const

内联函数

内存四区

new/delete

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
int *p = new init ;
p = new int (10);
delete p;

int  **pp = new int * [10]{NULL};
delete []pp;

 #include <iostream>


int * p = new std :: nothrowint[8748315031785743515];
//不抛出异常返回NULL
set_new_handler

表达式

求值的顺序

逻辑运算符

1
(a = 0)&&(b = 100)  //a= 0 赋值返回 a 为 0 ,为假

左值右值

显示转换

static_cast : 具有明确定义的类型转换(不能转换底层const) const_cast: 改变运算对象的底层const reinterpret_cast: 通常为运算对象的位模式提供较低层次上的重新 解释。 dynamic_cast: 支持运行时类型识别,常用于基类指针转向派生 类指针。

函数参数传递

传值参数

传引用参数

const形参和实参

函数返回类型

函数返回的值:返回的值用于初始化调用点的一个临时量,该临时量就是函数的返回值。不要返回局部对象的引用或指针