C++ Casting Operators和传统的C cast操作符

Ris*_*hta 6 c++ casting

可能重复:
什么时候应该使用static_cast,dynamic_cast和reinterpret_cast?

我做了很多谷歌搜索:

  1. 为什么要使用C++强制转换运算符而不是传统的C风格转换运算
  2. 何时使用C++强制转换运算符,一些实例?

以下是我发现的:

  • 传统上,任何C++转换运算符都用于更好地维护代码(即)我们可以通过搜索这种复杂符号(reinterpret_cast <)而不像C样式转换运算符,轻松找到代码中使用转换的位置.

现在让我简要介绍每个C++转换操作符的原因和时间

的static_cast:

为何使用它而不是C型铸造? static_cast用于执行相关类型之间的转换.

例子 :

 Class A {};
 Class B {};

 A* a = new A();
 B* b = static_cast<B*>(a); // Compiler error
 B* b1 = (A*)a;  // Works fine
 float f;
 int addr = (int)(&f); // Works fine
 int addr = static_cast<int>(&f);  // Compiler error
Run Code Online (Sandbox Code Playgroud)

但我想知道何时使用上述代码的真实用例?

reinterpret_cast:

reinterpret_cast 转换指向不相关类型的指针.

例子:

 Class A {};
 Class B {};

 A* a = new A();
 B* b = reinterpret_cast<B*>(a); // Works fine
 B* b1 = (A*)a;  // Works fine
 float f;
 int addr = (int)(&f); // Works fine
 int addr = reinterpret_cast<int>(&f);  // Works fine


 int ai = 10;
 float af = 13.33;
 // Would depend on how floating point is stored in machine
 // int& since reinterpret_cast expects either the type or operand to be pointer or reference 
 int ki = reinterpret_cast<int&>(af); // ki would not be 13
 int kitemp = (int)af; // kitemp would be 13

 // The same reinterpret_cast behaviour can be achieved using this,
 int* in = (int*)(af);
 cout << (*in);
Run Code Online (Sandbox Code Playgroud)

我的问题是reinterpret_castC风格铸造还有什么不同?我无法找到为什么要将它用于传统的铸造操作员以及何时使用它?

使这些运营商变得更糟的另一个重要例子是:

   const unsigned int * p;
   (int*)p; // Would remove unsigned and const at one shot
   // Using C++ casting operators
   // Const_cast expects a pointer or a reference
   reinterpret_cast<int*>(const_cast<unsigned int* >(p));
Run Code Online (Sandbox Code Playgroud)

编写上面的代码来删除,const并且unsigned 在C++编译中要复杂得多?那么,为什么人们使用reinterpret_cast,const_caststatic_cast在土产Ç铸造运营商?

我确实理解dynamic_cast在多态类的情况下使用; 再次,这个运营商也有额外的RTTI成本.

小智 8

谷歌的C++风格指南提供了使用C++样式转换的一些动机:

C演员的问题是操作的模糊性; 有时你正在进行转换(例如(int)3.5),有时候你正在进行转换(例如(int)"hello"); C++演员避免这种情况.另外,C++强制转换在搜索时更加明显.

我喜欢C++强制转换,因为它们使你打算做的非常明确,允许编译器捕获错误的用法.

例如,如果您知道只打算对整数进行数值转换,static_cast则只有在数字转换有意义时才会编译.正如您在示例代码中所示,无论有效性如何,C样式转换都将执行转换.

C++演员阵容实际上只是为了更好地记录意图,以及针对意外使用的编译时保护.