我应该真的使用static_cast每次我想在原始类型之间转换吗? [英] Should I really use static_cast every single time I want to convert between primitive types?

查看:291
本文介绍了我应该真的使用static_cast每次我想在原始类型之间转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么原因

long l = 1;
char c = static_cast<char>(l);

float f = 1.0f;
int i = static_cast<int>(f);

比这更好

long l = 1;
char c = (char)l;

float f = 1.0f;
int i = (int)f;

我有很多遗留代码,在类似的情况下使用第二种类型的类型转换,所以这也是一个问题,我应该或我可以不执行该代码的全面修订。

I've got much of legacy code that uses the second style for type casting in similar situations, so this is also a question about should I or may I not perform full-scale revision of that code.

推荐答案

面向未来的。

p>

Let's say in the future I do this:

float blah = 1.0f;
float* f = &blah;

现在, int i = static_cast< int>(f) code>停止编译,但 int i =(int)f; 会执行 reinterpret_cast

static_cast< int> 这正是我想要你做的(int)做任何你可以得到一个整数。对于后者,编译器会走出去让你获得一个 int 值,这很少(从不?)。

static_cast<int> is this is exactly what I want you to do. (int) is do whatever you can to get me an int. With the latter, the compiler will go out of its way to get you an int value, and that's rarely (never?) desirable.

这篇关于我应该真的使用static_cast每次我想在原始类型之间转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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