| 类型转换运算符 | 作用 | 语法 |
|---|---|---|
| dynamic_cast | 将派生类指针转换为基类指针,主要是为了确保可以安全的调用虚函数 | dynamic_cast(expression) |
| const_cast | 有时需要这样一个值,它在大多数时候是常量,有时又想要修改,这时可以将这个值声音为const,在需要修改的时候使用const_cast | const_cast(expression) |
| static_cast | 当type_name可被隐式转换为expression所属的类型或expression可被隐式转换为type_name所属的类型时,转换才合法,否则将出错 | static_cast(expression) |
| reinterpret_cast | 类似C语言中的指针指针类型转换,例如 int n = 20; char p = (char)&n;这里的(char*)即是C语言的强制类型转换语法 | reinterpret_cast(expression) |
注意:与通用转换机制相比,这四种转换提供了更安全,更明确的类型转换
dynamic_cast#includeconst_castusing namespace std; class CPerson { public: virtual void Show() { cout << "CPerson" << endl; } }; class CStudent : public CPerson { public: virtual void Show() { cout << "CStudent" << endl; } }; int main() { //! 将CStudent对象地址赋值给CPerson*:成功,返回CPerson*;失败,返回0(即空指针) CPerson *pPer = nullptr; if (pPer = dynamic_cast (new CStudent)) //< 转换成功再调用虚函数 { pPer->Show(); } return 0; }
int n = 10;
const int *p = &n;
// *p = 29; 错误,无法指针指向的值
int *p2 = const_cast(p);
*p2 = 29; //< 正确,可以删除const
static_cast
class CPerson{};
class CStudent: public CPerson{}; //< 继承CPerson
class CPond{}; //< 和Cperson,CStudent无关
int main()
{
CPerson per;
CStudent stu;
CPerson *pPer = static_cast(&stu); //< 合法
CStudent* pStu = static_cast(&per); //< 合法
// CPond *pPon = static_cast(&stu); //< 非法,CPond与CStudent不相关
return 0;
}
reinterpret_cast
通常,这样的转换适用于依赖于实现的底层编程技术,是不可移植的。例如,不同系统在存储多字节整形时,可能以不同的顺序存储其中的字节。并不支持所有的类型转换,例如,可以将指针类型转换为足以存储指针表示的整形,但不能将指针转换为更小的整数或者浮点型;另一个限制是,不能将函数指针转换为数据指针,反之亦然。
StuPer stuP = {10, 20};
cout << *(short*)((char*)(&stuP)+2) << endl; //< C语言的指针类型转换语法取short b值,输出为20
cout << *(reinterpret_cast( (reinterpret_cast(&stuP)+2))); //< c++ 指针类型转换语法,输出为20
参考书籍
C++ Primer Plus(第6版)——15.5 类型转换运算符



