C++ 类型转换

2018-03-24 11:17 更新

学习C++ - C++类型转换

当您为另一种算术类型的变量赋值一种算术类型的值时,C ++将转换值。

赋值给bool变量的零值将转换为false,并将非零值转换为true。

将浮点数转换为整数会导致截断数字。

当您在表达式中组合混合类型时,C ++会转换值。

当函数传递参数时,C ++会转换值。

例子

以下代码显示初始化时的类型更改


#include <iostream> 
using namespace std; 
int main() 
{ 
     cout.setf(ios_base::fixed, ios_base::floatfield); 
     float tree = 3;     // int converted to float 
     int guess(3.9);     // double converted to int 
     int debt = 7.2E12;  // result not defined in C++ 
     cout << "tree = " << tree << endl; 
     cout << "guess = " << guess << endl; 
     cout << "debt = " << debt << endl; 
     return 0; 
} 

上面的代码生成以下结果。

类型转换(Type Casts)

C++可以通过类型转换显式强制类型转换。

要将int值转换为long类型,可以使用以下任一表达式:

(long) my_value    // returns a type long conversion of my_value 
long (my_value)    // returns a type long conversion of my_value 

类型转换不会更改my_value变量本身。

它创建一个新的指示类型的值,然后您可以在表达式中使用,如下所示:

cout << int("Q");  // displays the integer code for "Q" 

更一般地,您可以执行以下操作:

(typeName) value     // converts value to typeName type 
typeName (value)     // converts value to typeName type 

第一种形式是直的C.第二种形式是纯C ++。

C++还引入了四种类型的转换操作符,它们在如何使用它们方面更具限制性。

static_cast <>运算符可用于将值从一个数字类型转换为另一个数字类型。

例如,将my_value转换为类型long值如下所示:

static_cast<long> (my_value)     // returns a type long conversion of my_value 

更一般来说,您可以执行以下操作:

static_cast<typeName> (value)        // converts value to typeName type 

以下代码说明了基本类型转换(两种形式)和static_cast <>。


#include <iostream> 
using namespace std; 
int main()
{ 
     int my_int, my_result, my_value; 

     // adds the values as double then converts the result to int 
     my_int = 19.99 + 11.99; 

     // these statements add values as int 
     my_result = (int) 19.99 + (int) 11.99;   // old C syntax 
     my_value = int (19.99) + int (11.99);  // new C++ syntax 
     cout << "my_int = " << my_int << ", my_result = " << my_result; 
     cout << ", my_value = " << my_value << endl; 

     char ch = "Z"; 
     cout << "The code for " << ch << " is ";    // print as char 
     cout << int(ch) << endl;                    // print as int 
     cout << "Yes, the code is "; 
     cout << static_cast<int>(ch) << endl;       // using static_cast 
     return 0; 
} 

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号