C++ “警告:在 g++ 中使用旧式强制转换”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5249418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:45:38  来源:igfitidea点击:

"warning: use of old-style cast" in g++

c++castingg++

提问by prosseek

Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?

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

With this C++ code,

有了这个 C++ 代码,

char* a = (char*) b;

I got warning warning: use of old-style cast.

我收到警告warning: use of old-style cast

What would be the new-style cast?

新风格的演员阵容是什么?

回答by Erik

reinterpret_cast, static_cast, dynamic_castand const_castare the c++ cast alternatives.

reinterpret_caststatic_castdynamic_cast并且const_cast是C ++投的替代品。

  • const_castto remove const/volatile from a const variable.
  • dynamic_castto perform runtime validity checks when casting in between polymorphic types
  • static_castto perform e.g up/down-cast in a inheritance hierarchy, but with no runtime checks, or to explicitly perform conversions that could be implicit (e.g. float to int)
  • reinterpret_castto convert in between unrelated types.
  • const_cast从 const 变量中删除 const/volatile。
  • dynamic_cast在多态类型之间进行转换时执行运行时有效性检查
  • static_cast在继承层次结构中执行例如向上/向下转换,但没有运行时检查,或者显式执行可能是隐式的转换(例如浮点到 int)
  • reinterpret_cast在不相关的类型之间进行转换。

Brief syntax example:

简要语法示例:

char* a = (char*) b; 
//would be 
char* a = static_cast<char*>(b);
//to remove the warning

回答by Nawaz

Read this topic to know about C++ style casts which come in various flavors:

阅读本主题以了解各种风格的 C++ 风格强制转换:

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

什么时候应该使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?