文章目录
- 一、概述
- 二、隐式类型转换(Implicit Conversion)
- 三、显式类型转换(Explicit Conversion)
- 四、C++ 风格类型转换
一、概述
C++ 提供了多种类型转换(Type Conversion)方式,以便在不同类型的数据之间进行转换。类型转换主要分为 隐式转换 和 显式转换(即强制转换)。其中,显式转换包括 C 风格转换、static_cast、dynamic_cast、const_cast 和 reinterpret_cast。
二、隐式类型转换(Implicit Conversion)
隐式转换是由编译器自动执行的类型转换,通常发生在以下几种情况:
- 基本类型转换:从低精度到高精度(如 int 转换为 double)。
- 算术转换:运算时,较低精度的类型会被转换为较高精度的类型(如 char 转换为 int)。
- 指针转换:int* 可以隐式转换为 void*,但 void* 不能隐式转换回 int*。派生类的指针可以隐式转换为基类指针(向上转型)。
- 布尔转换:非零整数转换为 true,零转换为 false。
- 非空指针转换为 true,空指针转换为 false。
示例:
int a = 10;
double b = a; // int 自动转换为 double
void* ptr;
int* pInt = &a;
ptr = pInt; // int* 隐式转换为 void*
三、显式类型转换(Explicit Conversion)
C++ 提供了多种强制转换方式,其中包括 C 风格转换和 C++ 提供的 static_cast、dynamic_cast、const_cast 和 reinterpret_cast。
C 语言中的类型转换使用 (type) 语法:
double d = 3.14;
int i = (int)d; // C 风格转换
C 风格转换的缺点:
- 不够安全,难以区分转换的类型。
- 可能会绕过 C++ 类型检查,导致潜在错误。
四、C++ 风格类型转换
1. static_cast
- 用途:用于相关类型之间的转换,如基本数据类型转换、类层次中的向上转换(派生类→基类指针/引用)、显式类型转换(无类型检查的向下转换)等。
- 语法:static_cast<目标类型>(表达式)
- 特点:编译时检查:不执行运行时类型检查,向下转换(基类→派生类)可能不安全。类层次中的向上转换(安全)。
示例:
double d = 3.14;
int i = static_cast<int>(d); // 安全的基本类型转换class Base {};
class Derived : public Base {};Derived dObj;
Base* bPtr = static_cast<Base*>(&dObj); // 向上转型
2. dynamic_cast
- 用途:主要用于多态类型(含虚函数的类)的向下转换或交叉转换(如兄弟类之间的转换)。
- 语法:dynamic_cast<目标类型>(表达式)
- 特点:运行时检查:转换失败时返回 nullptr(指针)或抛出 std::bad_cast(引用)。仅限多态类型:基类必须有虚函数(否则编译错误)
示例:
class Base {
public:virtual ~Base() {} // 必须有虚函数,才能使用 dynamic_cast
};class Derived : public Base {
public:void show() { std::cout << "Derived class" << std::endl; }
};Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {derivedPtr->show();
} else {std::cout << "Conversion failed!" << std::endl;
}
3. const_cast
用途:移除或添加 const/volatile 属性,常用于适配遗留代码或接口。 语法:const_cast<目标类型>(表达式)
注意事项:不修改原对象的常量性:若原对象为常量,通过指针/引用修改它是未定义行为。仅修改类型属性:不能改变实际类型(如 int* →double* 不可行)。
示例:
void modify(const int* p) {int* nonConstP = const_cast<int*>(p);*nonConstP = 42;
}int main() {int x = 10;modify(&x);std::cout << x << std::endl; // 输出 42
}
4. reinterpret_cast
- 用途:低级别、依赖实现的类型转换(如指针↔整数、无关指针类型之间的转换)。
- 语法:reinterpret_cast<目标类型>(表达式)
- 特点:高度不安全:不进行任何类型检查,可能导致未定义行为。使用场景极少:通常用于底层代码(如序列化、硬件访问)。
示例:
#include <iostream>int main() {int x = 42;int* p = &x;void* vp = reinterpret_cast<void*>(p); // int* → void*int* p2 = reinterpret_cast<int*>(vp); // void* → int*std::cout << *p2 << std::endl; // 输出 42
}