- 静态类型转换 static_cast
- 语法 static_cast<目标类型>(原变量/原对象)
- 允许父子之间的指针或者引用的转换
- 允许内置数据类型转换
- 动态类型转换 dynamic_cast
- 不允许内置数据类型转换
- 允许父子之间指针或者引用的转换
- 父转子 不安全的 转换失败
- 子转父 安全 转换成功
- 如果发生多态,总是安全,可以成功
- 语法 dynamic_cast<目标类型>(原变量/原对象)
- 常量转换 const_cast
- 只允许 指针或者引用 之间转换
- 语法 const _cast<目标类型>(原变量/原对象)
- 重新解释转换 reinterpret_cast
- 最不安全一种转换,不建议使用
#include<iostream>
#include<string>
using namespace std;
class father {};
class son:public father {};
class other {};
void test01() {
//静态类型转换
char c1 = 'c';
double d1 = static_cast<double>(c1);
cout << d1 << endl;
father *fp1=NULL;
son *sp1=NULL;
//子转父
father *fp2 = static_cast<father *>(sp1);
//父转子
son *sp2 = static_cast<son *>(fp1);
}
void test02() {
//动态类型转换,比静态类型转换更安全
// 不能转,不安全
//char c1 = 'c';
//double d1 = dynamic_cast<double>(c1);
//cout << d1 << endl;
father* fp1 = NULL;
son* sp1 = NULL;
//子转父
father* fp2 = dynamic_cast<father*>(sp1);
//父转子,不能转,不安全
//son* sp2 = dynamic_cast<son*>(fp1);
}
void test03() {
//不可以将非指针或非引用做const_cast转换
const int* p = NULL;
int* pp = const_cast<int*>(p);
const int* ppp = const_cast<const int*>(pp);
//const int a = 10;
//int b = const_cast<int>(a);
int num = 10;
int& numRef = num;
const int& num2 = const_cast<const int&>(numRef);
}
//重新解释转换 reinterpret_cast 最不安全一种转换,不建议使用
void test04() {
int a = 10;
int* p = reinterpret_cast<int*>(a);
father* fp = NULL;
other* op = reinterpret_cast<other *>(fp);
int* sp1 = new int;
other* ss= reinterpret_cast<other*>(sp1);
delete ss;
}
int main() {
test01();
test02();
test03();
test04();
system("pause");
return EXIT_SUCCESS;
}