W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
當(dāng)您為另一種算術(shù)類型的變量賦值一種算術(shù)類型的值時(shí),C ++將轉(zhuǎn)換值。
賦值給bool變量的零值將轉(zhuǎn)換為false,并將非零值轉(zhuǎn)換為true。
將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)會(huì)導(dǎo)致截?cái)鄶?shù)字。
當(dāng)您在表達(dá)式中組合混合類型時(shí),C ++會(huì)轉(zhuǎn)換值。
當(dāng)函數(shù)傳遞參數(shù)時(shí),C ++會(huì)轉(zhuǎn)換值。
以下代碼顯示初始化時(shí)的類型更改
#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++可以通過(guò)類型轉(zhuǎn)換顯式強(qiáng)制類型轉(zhuǎn)換。
要將int值轉(zhuǎn)換為long類型,可以使用以下任一表達(dá)式:
(long) my_value // returns a type long conversion of my_value long (my_value) // returns a type long conversion of my_value
類型轉(zhuǎn)換不會(huì)更改my_value變量本身。
它創(chuàng)建一個(gè)新的指示類型的值,然后您可以在表達(dá)式中使用,如下所示:
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)換操作符,它們?cè)谌绾问褂盟鼈兎矫娓呦拗菩浴?/p>
static_cast <>運(yùn)算符可用于將值從一個(gè)數(shù)字類型轉(zhuǎn)換為另一個(gè)數(shù)字類型。
例如,將my_value轉(zhuǎn)換為類型long值如下所示:
static_cast<long> (my_value) // returns a type long conversion of my_value
更一般來(lái)說(shuō),您可以執(zhí)行以下操作:
static_cast<typeName> (value) // converts value to typeName type
以下代碼說(shuō)明了基本類型轉(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é)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: