温馨提示×

C++类型转换运算符能用于哪些类型

c++
小樊
96
2024-11-09 05:44:35
栏目: 编程语言

C++ 类型转换运算符(type conversion operators)主要有四种:static_castdynamic_castconst_castreinterpret_cast。它们可以用于以下类型:

  1. static_cast

static_cast 是最常用的类型转换运算符,主要用于执行基础数据类型之间的转换(如 int 到 double)、空指针和空指针之间的转换、非多态类型的上下转换以及向上转型(将派生类对象转换为基类对象)。但是,它不能转换不相关的类型(如将 std::string 转换为 int)。

int num = 42; double d = static_cast<double>(num); // int to double int* p1 = nullptr; int* p2 = static_cast<int*>(p1); // nullptr to int* (unsafe) class Base {}; class Derived : public Base {}; Derived d; Base* b = static_cast<Base*>(&d); // Upcasting (Base* to Derived*) 
  1. dynamic_cast

dynamic_cast 主要用于在类的继承层次结构中执行向下转型(将基类对象转换为派生类对象)。它会在运行时检查转换的有效性,如果转换不安全,则返回空指针(对于指针类型)或抛出 std::bad_cast 异常(对于引用类型)。

class Base { virtual void foo() {} }; class Derived : public Base {}; Base* b = new Derived; Derived* d = dynamic_cast<Derived*>(b); // Downcasting (Base* to Derived*) 
  1. const_cast

const_cast 用于修改类型的常量性或易变性。它可以添加或删除类型的 constvolatile 修饰符。

const int num = 42; int* p = const_cast<int*>(&num); // Remove const from int* const char* str = "Hello, World!"; char* cstr = const_cast<char*>(str); // Remove const from char* (unsafe) 
  1. reinterpret_cast

reinterpret_cast 提供了一种低级别的类型转换,通常用于位模式的重新解释。它可以执行指针类型之间的转换(包括向上转型和向下转型)、整数类型与指针类型之间的转换以及同类型指针之间的转换。但是,reinterpret_cast 的转换行为很少是有定义的,因此在使用时要特别小心。

int num = 42; int* p = &num; char* c = reinterpret_cast<char*>(p); // Pointer to int to pointer to char float f = 3.14f; int* i = reinterpret_cast<int*>(&f); // Float to int (implementation-defined) 

请注意,在使用这些类型转换运算符时,务必确保转换的安全性,以避免产生未定义的行为或运行时错误。

0