當(dāng)您為另一種算術(shù)類型的變量賦值一種算術(shù)類型的值時,C ++將轉(zhuǎn)換值。
賦值給bool變量的零值將轉(zhuǎn)換為false,并將非零值轉(zhuǎn)換為true。
將浮點數(shù)轉(zhuǎn)換為整數(shù)會導(dǎo)致截斷數(shù)字。
當(dāng)您在表達式中組合混合類型時,C ++會轉(zhuǎn)換值。
當(dāng)函數(shù)傳遞參數(shù)時,C ++會轉(zhuǎn)換值。
以下代碼顯示初始化時的類型更改
#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;
}
上面的代碼生成以下結(jié)果。
C++可以通過類型轉(zhuǎn)換顯式強制類型轉(zhuǎn)換。
要將int值轉(zhuǎn)換為long類型,可以使用以下任一表達式:
(long) my_value // returns a type long conversion of my_value long (my_value) // returns a type long conversion of my_value
類型轉(zhuǎn)換不會更改my_value變量本身。
它創(chuàng)建一個新的指示類型的值,然后您可以在表達式中使用,如下所示:
cout << int("Q"); // displays the integer code for "Q"
更一般地,您可以執(zhí)行以下操作:
(typeName) value // converts value to typeName type typeName (value) // converts value to typeName type
第一種形式是直的C.第二種形式是純C ++。
C++還引入了四種類型的轉(zhuǎn)換操作符,它們在如何使用它們方面更具限制性。
static_cast <>運算符可用于將值從一個數(shù)字類型轉(zhuǎn)換為另一個數(shù)字類型。
例如,將my_value轉(zhuǎn)換為類型long值如下所示:
static_cast<long> (my_value) // returns a type long conversion of my_value
更一般來說,您可以執(zhí)行以下操作:
static_cast<typeName> (value) // converts value to typeName type
以下代碼說明了基本類型轉(zhuǎn)換(兩種形式)和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;
}
上面的代碼生成以下結(jié)果。
更多建議: