是否可以使用C型铸造内置类型? [英] Is it OK to use C-style cast for built-in types?

查看:85
本文介绍了是否可以使用C型铸造内置类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里阅读了很多关于C风格铸造在C ++中的答案我还有一个小问题。我可以对内置类型如 long x =(long)y; 使用C风格的转换,还是认为它是坏的和危险的?

After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?

推荐答案

我不会,原因如下:


  • 丑陋,应该是丑陋的,并在代码中脱颖而出,并且可以使用grep和类似工具查找。

  • 始终使用C ++转换是一个更容易记住的简单规则

  • C ++风格的转换为其他开发人员提供了更多的信息

  • C风格的Cast可能会允许您执行不需要的转换 - 如果您有一个接口(int *),而您正在使用c风格的转型传递一个const int *,并且界面改变为接受一个长*,你的代码使用c风格的casts将继续工作,即使它不是你想要的。

  • Casts are ugly and should be ugly and stand out in your code, and be findable using grep and similar tools.
  • "Always use C++ casts" is a simple rule that is much more likely to be remembered and followed than, "Use C++ casts on user-defined types, but it's OK to use C-style casts on built-in types."
  • C++ style casts provide more information to other developers about why the cast is necessary.
  • C-style casts may let you do conversions you didn't intend -- if you have an interface that takes in (int*) and you were using c-style casts to pass it a const int*, and the interface changes to take in a long*, your code using c-style casts will continue to work, even if it's not what you wanted.

这篇关于是否可以使用C型铸造内置类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆