Skip to content

cpp_cast

ShenYj edited this page Apr 16, 2024 · 1 revision

类型转换

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

    • (type)expression
    • type(expression)
  • C++中有4个类型转换符

    • static_cast
    • dynamic_cast
    • reinterpret_cast
    • const_cast

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

const_cast

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

const Person *p1 = new Person();
p1->m_age = 10;

Person *p2 = const_cast<Person *>(p1);
p2->m_age = 20;

dynamic_cast

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

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

class Student: public Person { };

class Car { };

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

    Student *stu1 = dynamic_cast<Student *>(p1); // NULL
    Student *stu2 = dynamic_cast<Student *>(p2);
    Car *car = dynamic_cast<Car *>(p1);          // NULL
}

static_cast

类似于强制转换

  • 对比dynamic_cast,缺乏运行时安全检测
  • 不能交叉转换(不是同一继承体系的,无法转换)
  • 常用于基本数据类型的转换、非const转成const
  • 使用范围较广
int a = 10;
const double d = static_cast<double>(a);

Person *p1 = new Person();
Person *p2 = new Student();

Student *stu1 = static_cast<Student *>(p1);
Student *stu2 = static_cast<Student *>(p2);
Car *car = static_cast<Car *>(p1);

reinterpret_cast

  • 属于比较底层的强制转换,没有任何类型检查和格式转换,仅仅是简单的二进制数据拷贝
  • 可以交叉转换
  • 可以将指针和整数互相转换
Person *p1 = new Person();
Person *p2 = new Student();
Student *stu1 = reinterpret_cast<Student *>(p1);
Student *stu2 = reinterpret_cast<Student *>(p2);
Car *car = reinterpret_cast<Car *>(p1);

int *p = reinterpret_cast<int *>(100);
int *num = reinterpret_cast<int>(p);

int i = 10;
/// 不同类型之间转换可能会报错,所以类型改为引用类型, 但是最终d1的值实际并非10,多了四个字节的垃圾值
double d1 = reinterpret_cast<double &>(i);

Getting Started

Social

Clone this wiki locally