将数值转换为其他类型称为类型转换(Casting)。在 C++ 中,有几种方法可以进行数值类型转换

隐式类型转换

当编译器能够自动将一个类型转换为另一个类型时,会发生隐式类型转换。例如,将一个 int 赋值给一个 float 变量时,int 会被隐式转换float

C++
int i = 10;
float f = i; // i 被隐式转换为 float

显式类型转换

显式类型转换(也称为强制类型转换)是程序员明确指定将一个类型转换为另一个类型。C++ 中有几种显式类型转换的方式:

1. C 风格的类型转换

C++
float f = 3.14;
int i = (int)f; // 将 f 强制转换为 int

2. C++ 风格的类型转换

C++ 提供了四种类型转换运算符,可以更精确地控制类型转换

  • static_cast:用于执行静态类型转换,例如将 int 转换float,或者在具有继承关系的类之间进行转换
  • dynamic_cast:用于在具有多态性的类之间进行转换,通常用于将基类指针或引用转换为派生类指针或引用。
  • reinterpret_cast:用于执行低级类型转换,例如将指针转换为整数,或者在不相关的类型之间进行转换
  • const_cast:用于移除或添加 const 限定符。
C++
float f = 3.14;
int i = static_cast<int>(f); // 使用 static_cast 将 f 转换为 int

CRType* pCR = dynamic_cast<CRType*>(pBase); // 使用 dynamic_cast 进行多态类型转换

intptr_t iPtr = reinterpret_cast<intptr_t>(pCR); // 使用 reinterpret_cast 将指针转换为整数

const int ci = 10;
int* pi = const_cast<int*>(&ci); // 使用 const_cast 移除 const 限定符

注意事项

  • 在进行类型转换时,需要注意数据类型的范围和精度,避免数据丢失或溢出。
  • 尽量使用 C++ 风格的类型转换运算符,它们可以提供更精确的控制和类型检查。
  • 避免在不相关的类型之间进行转换,除非你清楚地知道自己在做什么。

示例

C++
int main() {
  int i = 10;
  float f = 3.14;

  // 隐式类型转换
  float f2 = i; // i 被隐式转换为 float

  // 显式类型转换
  int i2 = static_cast<int>(f); // 使用 static_cast 将 f 转换为 int

  // 输出结果
  std::cout << "i: " << i << std::endl;
  std::cout << "f: " << f << std::endl;
  std::cout << "f2: " << f2 << std::endl;
  std::cout << "i2: " << i2 << std::endl;

  return 0;
}

这段代码演示了隐式类型转换和显式类型转换的用法。f2 的值为 10.0,i2 的值为 3。

希望以上信息对您有所帮助!

最后修改: 2025年01月30日 星期四 16:18