类型转换

const_cast

用于将const指针或饮用转换成非const

用法:

1
2
3
const int a = 10;
int *b = const_cast<int *>(&a);
*b = 20;

reinterpret_cast

重新解释类型,既不检查指向的内容,也不检查指针类型本身;但要求转换前后的类型所占用内存大小一致,否则将引发编译时错误。

很危险!!

用法

1
2
3
4
5
6
7
8
9
10
int test(int i) {
return 1;
}


int main() {
// reinterpret_cast
typedef int (*FucP)();
FucP fucP = reinterpret_cast<FucP>(&test);
}

函数指针

函数指针和其他指针一样定义之后使用之前也是需要初始化。

函数指针有两个用途:调用函数和做函数的参数

1
2
3
4
5
int (*fun)(int x,int y) //函数指针的定义
fun = &Function //函数指针的赋值方式1
fun = Function //函数指针的赋值方式2
x = (*fun)() //函数指针的调用方式1
x = fun() //函数指针的调用方式21.2.3.4.5.1.2.3.4.5.

函数赋值的时候取地址运算符&不是必需的,因为一个函数标识符就表示了它的地址,并且赋值的时候函数不需要带圆括号;

如果是函数调用,还必须包含一个圆括号括起来的参数表。