所以我有这段代码
char [] a = {'a','b','c'};
char c = 'a' + 'b'; //works
char c2 = 98 + 97; //works
char c3 = a[0] + a[1]; //compile time error
所以它们都是相同的功能,但是在获取和使用数组值时它会给我一个编译时错误。这是什么原因??
The result of the additive operator applied two char operands is an int.
那我为什么可以这样做呢?
char c2 = (int)((int)98 + (int)97);
最佳答案
The result of the additive operator applied two char
operands is an int
.
Binary numeric promotion is performed on the operands. The type of an additive expression on numeric operands is the promoted type of its operands
前两个是常量表达式,其结果值是 int
,可以安全地分配给 char
。
第三个不是常量表达式,因此编译器无法保证。
同理
then why can I do this?
char c2 = (int)((int)98 + (int)97);
这也是一个常量表达式,结果可以放在 char
中。
尝试使用更大的值,12345
和 55555
。
关于java - 从数组中赋值时出现 Char 数组编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196798/