本文介紹了可以將整數值分配給 char 但不能將整數變量分配給 char的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
為什么下面的代碼編譯不出來
Why doesn't the following code compile
int n = 5;
char c = n;
但以下確實編譯
char c = 5;
我不是在這兩種情況下都給 char 分配了一個整數值嗎?
Aren't I just assigning an integer value to char in both cases?
推薦答案
可以將 char
分配給 int
而無需強制轉換,因為這是一種擴大轉換.反過來,將 int
轉換為 char
需要強制轉換,因為它是一種縮小轉換.
A char
can be assigned to an int
without a cast because that is a widening conversion. To do the reverse, an int
to a char
requires a cast because it is a narrowing conversion.
另請參閱 JLS.第 5 章.轉化和促銷.
這篇關于可以將整數值分配給 char 但不能將整數變量分配給 char的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!