C语言风格的类型转换符号

(type)expressiontype(expression)

int main()
{
    double a = 1.1;
    int b = (int) a;
    int c = int(a);
    return 0;
}

C++中有4个类型转换符号

  1. static_cast
  2. dynamic_cast
  3. reinterpret_cast
  4. const_cast

使用格式:xx_cast<type>(expression)

const_cast

一般用于去除const属性,将const转换成非const

class Point{};

int main()
{
    const Point *p = new Point();
    // Point *p2 = p; 不被允许
    Point *p2 = const_cast<Point *>(p);
    // 等于下面的
    // Point *p2 = (Point *)p;
    return 0;
}

dynamic_cast

一般用于多态类型的转换,有运行时安全检测。

class Person
{
    virtual void run() {  }
};

class Student : public Person{};

int main()
{
    Person *p1 = new Person();
    Person *p2 = new Student();

    printf("p1 = %X\np2 = %X\n", p1, p2);
    // 检查到不安全,直接赋空。
    Student *stu1 = dynamic_cast<Student *>(p1);
    Student *stu2 = dynamic_cast<Student *>(p2);

    printf("stu1 = %X\nstu2 = %X\n", stu1, stu2);
    return 0;
}
// 输出
// p1 = D213E0
// p2 = D21400
// stu1 = 0
// stu2 = D21400

static_cast

对比dynamic_cast,缺乏运行时安全检测。

不能交叉转换(不是同一继承体系的,无法转换)A类与B类没有继承关系,相互之间转换,称为交叉转换。

常用于基本数据类型的转换、非const转成const

适用范围广。

reinterpret_cast

属于比较底层的强制转换,没有任何类型检查和格式转换,仅仅是简单的二进制数据拷贝。

可以交叉转换。

可以将指针和整数互相转换。