目录
reinterpret_cast类型转换符的使用
从字面意思去理解“reinterpret_cast类型转换符”的含义
代码示例
reinterpret_cast类型转换符的使用
从字面意思去理解“reinterpret_cast类型转换符”的含义
Re+interpret汉语意思意为“重新编译”。这个类型转换符和C语言的强制类型转换极为相似,表示:“不管什么类型,相不相关,都直接暴力地强制类型转换”,但是这样的结果可能非常糟糕。
例如:reinterpret_cast的使用使得“基类指针强转为派生类的指针”成为可能,但是转化而来的指针虽然表面上是派生类指针,但是内容可能因为未完全初始化的原因充满了不确定性,还有你可以通过这个转换符将“int”类型转换为“基类类型”但是这样做仅仅是为了编译通过,当我们使用这个变量去调用基类成员时,均会报错。
代码示例
#include <iostream>
#include <string>
using namespace std; class Cperson
{
private: string name; int age;
public: Cperson(string name, int age) { this->name = name; this->age = age; } virtual ~Cperson() // 详细请参考我的“虚析构函数”这篇文章 { cout << "调用Cperson析构函数" << endl; } virtual void ShowInf() { cout << this->name << "的年龄为" << this->age << endl; }
}; class Cstudent : public Cperson
{
private: float mark;
public: Cstudent(float mark, string name, int age) :Cperson(name, age) { this->mark = mark; } ~Cstudent() { cout << "调用Cstudent的析构函数" << endl; } void ShowInf() { cout << "该学生的成绩为" << this->mark << endl; }
}; int main()
{ Cperson *person = new Cperson("超级霸霸强", 19); Cstudent *stud = reinterpret_cast<Cstudent*>(person); // 用派生类指针强制转换为基类指针,可通过编译,但会带来无穷的隐患 Cperson *person1; Cstudent *stud1 = dynamic_cast<Cstudent*>(person); // dynamic_cast有检查错误的功能 if (stud1==NULL) { cout << "指针类型转换失败" << endl; } // 用其他类型转换符,类型转换失败
}