const_cast
const_cast / volatile_cast:修改类型的const或volatile属性,返回一个指向非const对象的指针或引用,此时可以通过该指针或引用改变其数据。
int numA = 3;
const int* ptr1 = &numA;
int* ptr2 = const_cast<int*>(ptr1);
const int numB = 3;
int& numb = const_cast<int&>(numB);
static_cast
把一个表达式转换为某种类型,但没有运行时类型检查来保证转换的安全性。
- 用于类层次结构中基类和派生类之间的指针或引用的转换:
- 进行向上转换(将派生类的指针或引用转换成基类)是安全的;
- 进行向下转换(将基类的指针或引用转换为派生类)是不安全的。
- 用于基本数据类型间的转换;
- 用于把空指针转换成目标类型的空指针;
- 用于把任何类型的表达式转换为void类型。
class Parent {};;
class Child :public Parent {};
Parent* parent;
Child* child;
//派生类 to 基类,向上转换,安全
Parent* CtoP = static_cast<Parent*>(child);
//基类 to 派生类,向下转换,不安全
Child* PtoC = static_cast<Child*>(parent);
//基本类型转换
int num = 1;
char c = static_cast<char>(num);
//空指针的转换
void* voidPtr;
int* intPtr = static_cast<int*>(voidPtr);
voidPtr = static_cast<void*>(intPtr);
static_cast不能转换掉变量的const、volatile、_unaligned属性。
dynamic_cast
用于类层次结构中基类和派生类之间的指针或引用的转换,dynamic_cast会根据基类指针是否真正指向派生类指针来做相应的处理。dynamic_cast运算符的类型必须是类的指针、类的引用或是void*。该运算符可以在执行期决定真正的类型,如果向下转换是安全的,返回适当转型过的指针,如果不是安全的,则返回空指针。
-
用于类层次间进行向上转换,效果同static_cast;
-
用于类层次间进行向下转换,具有类型检查功能,更安全;
基类一定要有虚函数,否则会编译出错;static_cast没有这个限制。
-
用于交叉转换:派生类之间的转换。
class Parent {
virtual ~Parent() {};
};
class Child :public Parent {};
class Child2 :public Parent {};
Parent* parent;
Child* child;
Child2* child2;
//派生类 to 基类,向上转换,安全
Parent* CtoP = dynamic_cast<Parent*>(child);
//基类 to 派生类,向下转换,安全,基类必须有虚函数
Child* PtoC = dynamic_cast<Child*>(parent);
Child2* CtoC = dynamic_cast<Child2*>(child2);
//无法通过static_cast实现派生类之间的转换
//Child2* CtoC_SC = static_cast<Child2>(child2);
reinterpret_cast
C++中的强制类型转换,运算符的类型必须是一个指针、引用、算术类型、函数指针、成员指针,可以把一个指针转换成一个整数,也可以把一个整数转换为一个指针…
int num = 1;
int* intPtr = reinterpret_cast<int*>(num);
num = reinterpret_cast<int>(intPtr);