目录
一、静态类型转换
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test01()
{
char a = 'c';
int b = static_cast<int>(a);
cout << "b = " << b << endl;
}
class Base{};
class Son : public Base{};
class Other{};
void test02()
{
Base* base = NULL;
Son* son = NULL;
//1、向下类型转换 不安全
//父子之间的指针或者引用可以转换
Son* son2 = static_cast<Son*>(base);
//2、向上类型转换 安全
Base* base2 = static_cast<Base*>(son);
//3、Base*转成Other*
//Other other = static_cast<Other>(base); //转换无效
}
int main()
{
//test01();
system("pause");
return EXIT_SUCCESS;
}
二、动态类型转换
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test01()
{
char a = 'a';
//动态类型转换 不允许内置数据类型之间转换
//int b = dynamic_cast<int>(a);
}
class Base { virtual void fun() {} };
class Son : public Base { void fun() {} };
class Other{};
void test02()
{
Base* base = NULL;
Son* son = NULL;
//1、向下类型转换 不安全
//Son* son2 = dynamic_cast<Son*>(base); //转换无效
Son* son2 = dynamic_cast<Son*>(base); //发生多态的情况是安全的
//2、向上类型转换 安全
Base* base2 = dynamic_cast<Base*>(son);
//3、Base*转Other*
//Other* other = dynamic_cast<Other*>(base); //转换无效
}
int main()
{
system("pause");
return EXIT_SUCCESS;
}
三、常量转换和重新解释转换
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test01()
{
//不可以将非指针或非引用做const_cast转换
const int* p = NULL;
int* pp = const_cast<int*>(p);
const int* ppp = const_cast<const int*>(pp);
//const int a = 10;
//const int b = const_cast<int>(a);
int num = 10;
int& numRef = num;
const int& num2 = const_cast<const int&>(numRef);
}
//重新解释转换 最不安全的一种转换 不建议使用
class Base{};
class Other{};
void test02()
{
int a = 10;
int* b = reinterpret_cast<int*>(a);
Base* base = NULL;
Other* other = reinterpret_cast<Other*>(base);
}
int main()
{
system("pause");
return EXIT_SUCCESS;
}