c++为了约束合理地类型转换,尽量减少不合法地类型转换,提供了四种类型转换运算符。
dynamic_cast;
const_cast;
static_cast;
reinterpret_cast
下面我们对上述4中类型转换运算符从简单到繁杂做一个介绍。
const_cast
const_cast运算符用于执行只有一种用途的类型转换,即改变值为const或volatile。
简单来讲就是去除const,使用的对象为指针或者引用。
语法如下:
const_cast<type-name>(expression)
它要求转换前后以及传入的type-name三者为相同的类型。如:
Parent parent;
const Parent* pParent = &parent;
Parent* nonConstParent = const_cast<Parent>(pParent);
//下面这种情况三者类型不同就是不合法地
Child* child = const_cast<Parent>(pParent); --------- 不合法
dynamic_cast
dynamic_cast主要用于向上转型,也就是把子类转换为基类。
但是这种转换是有条件的,就是要求子类继承基类的方式为公有继承,否则在编译期会报错。
语法如下:
dynamic_cast<type-name>(expression)
示例:
class Parent {}
class Child : public Parent {}
int main()
{
Child* child = new Child();
Parent* parent = dynamic_cast<Parent*>(child);
}
static_cast
static_cast用于替代隐式转换。
如下面三种情况:
1. 父类和子类之间的相互转换。
2. 枚举值和整型之间的相互转换。
3. 数值之间的转换。
语法如下:
static_cast<type-name>(expression)
reinterpret_cast
reinterpret_cast运算符用于天生危险的类型转换。它依赖于实现的底层编程技术,是不可移植的。除了不能移除const以及少数其他几种情况下,任何指针类型都可以使用reinterpret_cast进行转型。
无论转换合理与否,编译期和运行期都不会报错,只是得到的结果不太合理。
不能使用的几种情况:
1. 不能将指针转换为更小的整型或浮点型。
2. 不能将函数指针转换为数据指针,反之亦然。
语法如下:
reinterpret_cast <type-name>(expression)
网友评论