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
"warning: use of old-style cast" in g++
提问by prosseek
Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?
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_cast
and const_cast
are the c++ cast alternatives.
reinterpret_cast
,static_cast
,dynamic_cast
并且const_cast
是C ++投的替代品。
const_cast
to remove const/volatile from a const variable.dynamic_cast
to perform runtime validity checks when casting in between polymorphic typesstatic_cast
to 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_cast
to 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?