C / C ++中的显式类型转换运算符 [英] Explicit type casting operator in C/C++

查看:110
本文介绍了C / C ++中的显式类型转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将浮点类型 7.5 转换为整数值 7 ,其余部分丢失。在这里,类型转换运算符是 int 。我知道这是C ++中的有效类型转换。

The following code converts the float type 7.5 to an integer value 7, the remainder is lost. Here, the typecasting operator is int. I know it is valid typecast in C++.

int main()
{
        int i;
        float f = 7.5;
        i = (int) f; // Valid in C/C++
}

C / C ++ 将在要根据类型转换的表达式之前使用功能符号,并在表达式之间加上括号:

But another way to do the same thing in C/C++ is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses:

i = int (f); // It is worked in C++ but not C

因此,我有一个问题,

So, I have a question, Is it valid way to typecast in C++?

推荐答案

i = int (f);

在C ++中有效,但在C中无效。

is valid in C++ but not in C.

从C99标准开始, 6.5.4 Cast操作符


 cast-expression:
      unary-expression
      ( type-name ) cast-expression


C ++支持上述形式的转换以及函数样式的转换。函数样式转换就像调用类型的构造函数以在对象上进行构造。

C++ supports the above form of casting as well as function style casting. Function style casting is like calling the constructor of a type to construct on object.

查看以下使用C和C ++编译的块代码。

Check out the following block code compiled using C and C++.

#include <stdio.h>

int main()
{
   float f = 10.2;
   int i = int(f);

   printf("i: %d\n", i);
}

非工作C程序: http://ideone.com/FfNR5r

正在使用的C ++程序: http://ideone.com/bSP7sL

Working C++ program: http://ideone.com/bSP7sL

这篇关于C / C ++中的显式类型转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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