7、不一样的C++系列--C++类型转换

xiaoxiao2021-02-28  89

C++中的类型转换


强制类型转换


C方式的强制类型转换 (Type)(Expression)Type (Expression)

发一个非常粗暴的转换栗子:

typedef void(PF)(int); struct Point { int x; int y; }; int v = 0x12345; PF* pf = (PF*)v; char c = char(v); Point* p = (Point *)v; C方式强制类型转换存在的问题 过于粗暴 任意类型之间都可以进行转换,编译器很难判断其正确性难于定位 在源码中无法快速定位所有使用强制类型转换的语句

新的类型转换

C++将强制类型转换分为4种不同的类型 static_castconst_castdynamic_castreinterpret_cast

用法: xxx_cast < Type > (Expression)

static_cast 强制类型转换 用于基本类型间的转换不能用于基本类型指针间的转换用于有继承关系类对象之间的转换和类指针之间的转换const_cast 强制类型转换 用于去除变量的只读属性强制转换的目标类型必须是指针或引用reinterpret_cast 强制类型转换 用于指针类型间的强制转换用于整数和指针类型间的强制转换dynamic_cast 强制类型转换 用于有继承关系的类指针间的转换用于有交叉关系的类指针间的转换具有类型检查的功能需要虚函数的支持

举一个栗子:

#include <stdio.h> void static_cast_demo() { int i = 0x12345; char c = 'c'; int* pi = &i; char* pc = &c; //可以正确转换 c = static_cast<char>(i); //不能正确转换,因为static_cast只能用于基本类型间的转换 pc = static_cast<char*>(pi); } void const_cast_demo() { const int& j = 1; //可以正确转换 因为是去除引用的const属性 int& k = const_cast<int&>(j); const int x = 2; //可以正确转换,因为是去除引用的const属性 int& y = const_cast<int&>(x); //转换错误,因为不能用于去除基本类型的const属性 int z = const_cast<int>(x); k = 5; //输出 5 5 printf("k = %d\n", k); printf("j = %d\n", j); y = 8; //输出 2 因为x是常量,为了兼容c,直接取的符号表中的值 printf("x = %d\n", x); //输出8 printf("y = %d\n", y); //输出2个一样的地址 printf("&x = %p\n", &x); printf("&y = %p\n", &y); } void reinterpret_cast_demo() { int i = 0; char c = 'c'; int* pi = &i; char* pc = &c; //可以正确转换,是指针之间的转换 pc = reinterpret_cast<char*>(pi); //可以正确转换,是指针之间的转换 pi = reinterpret_cast<int*>(pc); //可以正确转换,因为是整数与指针之间的转换 pi = reinterpret_cast<int*>(i); //转换错误,因为是基本类型间的转换 c = reinterpret_cast<char>(i); } void dynamic_cast_demo() { int i = 0; int* pi = &i; //转换错误,类型不匹配 char* pc = dynamic_cast<char*>(pi); } int main() { static_cast_demo(); const_cast_demo(); reinterpret_cast_demo(); dynamic_cast_demo(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-65950.html

最新回复(0)