static_cast 用于内置的数据类型
还有具有继承关系的指针或者引用
代码如下:
#include <iostream>
using namespace std;class Building {};
class Animal{};
class Cat:public Animal{};int main()
{int a = 97;char c = static_cast<char>(a);cout << c << endl;int *p = nullptr;//char *sp = static_cast<char*>(p); 转不了Building *building = nullptr;//Animal *ani = static_cast<Animal *>(building); 转不了//父类指针转成子类指针Animal *ani = nullptr;Cat *cat = static_cast<Cat*> (ani);//子类指针转成父类指针Cat *soncat = nullptr;Animal *anifather = static_cast<Animal *> (soncat);Animal aniobj;Animal &aniref = aniobj;Cat&cat = static_cast<Cat &>(aniref);Cat catobj;Cat & catref = catobj;Animal & anifather2 = static_cast<Animal &> (catref);return 0;
}
dynamic_cast 转换具有继承关系的指针或者引用,在转换前会进行对象类型检查,只能由子类型转换为基类型。
子类指针可以转换为父类指针(从大到小),类型安全。
父类指针转成子类指针(从小到大),不安全。
代码如下:
#include <iostream>
using namespace std;class Building {};
class Animal{};
class Cat:public Animal{};int main()
{int a = 10;//char c = dynamic_cast<char>(a); 转换不了Animal *ani = nullptr;//Building *building = dynamic_cast<Building *>(ani); 转换不了Animal * ani = nullptr;//Cat * cat = dynamic_cast<Cat *>(ani); 转换不了Cat * cat = nullptr;Animal *ani = dynamic_cast<Animal*>(cat);return 0;
}
const_cast增加或者去除变量的const性。
代码如下:
#include <iostream>
using namespace std;class Building {};
class Animal{};
class Cat:public Animal{};int main()
{int a = 10;const int &b = a;int &c = const_cast<int &>(b);c = 20;cout << a << endl;cout << b << endl;cout << c << endl;const int *p = nullptr;int *q = const_cast<int*>(p);int *p3 = nullptr;const int *p4 = const_cast<const int *>(p3);return 0;
}
reinterpret_cast 强制类型转换
代码如下:
#include <iostream>
using namespace std;class Building {};
class Animal{};
class Cat:public Animal{};int main()
{Building *building = nullptr;Animal *ani = reinterpret_cast<Animal *> (building);typedef void(*FUNC1)(int, int);typedef int(*FUNC2)(int, char*);FUNC1 func1;FUNC2 func2 = reinterpret_cast<FUNC2>(func1);return 0;
}