什么是C ++中的Casting运算符?

强制转换是强制将一种数据类型转换为另一种数据的特殊运算符。作为运算符,类型转换是一元的,并且与任何其他一元运算符具有相同的优先级。

大多数C ++编译器支持的最通用的转换如下-

(type) expression

其中type是所需的数据类型。C ++还支持其他转换运算符,它们在下面列出-

  • const_cast <type>(expr)-const_cast运算符用于显式覆盖类型转换中的const和/或volatile。除了更改其const或volatile属性外,目标类型必须与源类型相同。这种类型的转换可操纵要设置或删除的传递对象的const属性。

  • dynamic_cast <type>(expr)-dynamic_cast执行运行时强制转换,以验证强制转换的有效性。如果无法进行强制类型转换,则强制类型转换将失败,并且表达式的结果为null。dynamic_cast对多态类型执行强制类型转换,并且仅当所指向的对象实际上是B对象时,才可以将A *指针强制转换为B *指针。

  • reinterpret_cast <type>(expr)-reinterpret_cast运算符将指针更改为任何其他类型的指针。它还允许从指针转换为整数类型,反之亦然。

  • static_cast <type>(expr)-static_cast运算符执行非多态转换。例如,它可以用于将基类指针转换为派生类指针。

示例

这些演员阵容非常具体。让我们考虑一个由编译器实现的强制转换示例-

#include <iostream>
using namespace std;
main() {
   double a = 21.09399;
   float b = 10.20;
   int c ;
   c = (int) a;
   cout << "Line 1 - Value of (int)a is :" << c << endl ;
   c = (int) b;
   cout << "Line 2 - Value of (int)b is  :" << c << endl ;
   return 0;
}

输出结果

这将给出输出-

Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is  :10