一.static_cast实现
static_cast:用于一般数据类型(int,float,char,string,double)、具有继承关系的指针或引用。
//static_cast
void test01() {
int a = 65;//A的ASCII值是65
char c = static_cast<char>(a);
cout << c << endl;
}
结果:
二.dynamic_cast实现
转换具有继承关系的指针或引用,在转换前会进行对象类型检查,只能由子类转父类。
由父类指针转子类会出错,类型不安全(有小到大)
由子类指针转父类指针不会出错,类型安全(由大到小)
注意:static_cast也可以转换具有继承关系的指针和引用,并且可以由父类转换为子类。
三.const_cast实现
const_cast 指针、引用或对象指针;
const_cast作用:用一个新变量增加或去除原来变量的const性;
//const_cast 指针、引用或对象指针
void test03() {
//基础数据类型
int a = 10;
const int& b = a;
//b = 1;
int& c = const_cast<int&>(b);
c = 20;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl;
//指针 用一个新变量增加或去除原来变量的const性
const int* p1 = nullptr;
int* p2 = const_cast<int*>(p1);
int* p3 = nullptr;
const int* p4 = const_cast<const int*>(p3);
}
四.reinterpret_cast实现
强制类型转换,无关的指针类型,包括函数指针都可以转换。
class Building{};
class Animal{};
class Cat:public Animal{};
//reinterpret_cast 强制类型转化
typedef void(*func1)(int, int);//函数指针
typedef int(*func2)(int, char*);
void test04() {
//1.无关的指针类型都可以进行转换
Building* building = nullptr;
Animal* ani = reinterpret_cast<Animal*>(building);
//2.函数指针的转换
func1 f1;
func2 f2 = reinterpret_cast<func2>(f1);
}
五.原则
- 程序员必须清楚的知道要转变的变量,转换前是什么类型,转换后是什么类型,以及转换后什么后果。
- 一般情况下,不建议类型转换,避免进行类型转换。