是否可以完全避免C ++中的C ++类型转换? [英] Is it possible to completely avoid C-style casts in C++?

查看:147
本文介绍了是否可以完全避免C ++中的C ++类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不相信有可能在编写C ++时完全避免C风格的转换。我很惊讶找出我需要使用C风格的转换,以避免编译器截断警告:

  short value_a = 0xF00D; // VS2008中的截断警告
short value_b = static_cast< short>(0xF00D); // VS2008中的截断警告
short value_c =(short)0xF00D; //没有警告!

是否有其他情况下没有C风格的C风格的转换? p>

解决方案

你只是试图模糊你的代码,它是那么简单。编译器是完全正确的告诉你这样。



如果你有一个精确的想法分配的值应该是什么,使用它。我的猜测是,你有一些毫无根据的假设 short 是16位宽,目标机器的符号表示是二的补码。如果是这样,请将-4083赋给您的变量。如果你只需要你的变量作为一个位向量,使用一个无符号类型。



就C来说,标准只是简单地说从一个整数类型转换到另一个:


否则,新类型被签名,
的值不能在其中表示;
结果是
实现定义或
实现定义的信号是


我想象C ++的观点在这方面没有太大的不同。其他答案提到边界情况下,在C + +你需要一个C风格的演员,以推翻C ++给你的所有类型检查。感觉对他们的需要是一个不好的设计的表现。



你给出的例子肯定不是一个我会找到任何有效的情况。 p>

I do not believe that it is possible to completely avoid C-style casts when writing C++. I was surprised to find out that I needed to use a C-style cast to avoid a compiler truncation warning:

short value_a = 0xF00D;                     // Truncation warning in VS2008
short value_b = static_cast<short>(0xF00D); // Truncation warning in VS2008
short value_c = (short)0xF00D;              // No warning!

Are there other scenarios where there is no C++-style substitute for a C-style cast?

解决方案

You are just trying to obfuscate your code, it is as simple as that. And the compiler is completely correct in telling you so.

If you have a precise idea what the assigned value should be, use that. My guess is that you have some unfounded presumption of short being 16 bit wide and that the sign representation of the target machine is two's complement. If that is so, assign -4083 to your variable. If you just need your variable as a bit vector, use an unsigned type.

As far as C is concerned the standard simply says about conversion from one integer type to another:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

I imagine the the point of view of C++ with this respect is not much different. Other answers mention border cases where in C++ you would need a `C'-style cast to overrule all typechecks that C++ gives you. Feeling the need for them is an indication of bad design.

The case that you give as an example is certainly not one for which I would find any valid circumstances.

这篇关于是否可以完全避免C ++中的C ++类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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