0

考虑以下

public byte GetAByte()
{
    return (byte)(_globalByte % 13);
}

请注意,以下内容将不起作用并引发错误。

    return (_globalByte % (byte)13);

这里 mod 运算符返回一个整数,需要将其转换回一个字节才能使 return 语句起作用。如果我错了,请纠正我,但我猜测 _globalByte 在计算模数之前被转换为整数。这总共意味着 2 次铸造操作。

所以我的问题是为什么基本运算符每次都必须返回一个整数?这是Java特有的怪癖,还是这样做有一些重要性?

4

2 回答 2

5

So my question is why do the basic operators have to return an integer every time? Is this is a quirk specific to java, or is there some importance for doing it this way?

The reason it happens is that the Java integral arithmetic operators are defined as int op int -> int (or long op long -> long).

Why they defined it that way? I'm not sure, but I can think of three possible explanations:

  • Efficient implementation across a range of native instruction sets / architectures.
  • Consistency with other languages like C and C++. (I'm not an expert on the standards for these languages, but I found the place in the C99 language spec which says this ... section 6.3.1.1 para 2.)
  • Mathematical consistency.

IMO, the latter is probably the most significant.

Suppose that there was an overload for + with signature byte op byte -> byte. Now we have a situation where + is no longer associative. Assume that we have byte b1, b2; int i; then

  • (b1 + b2) + i does the first + using the byte operator, and then the second + using the int operator.

  • b1 + (b2 + i) does the second + using the int operator, and then the first + using the int operator.

Note that if bytewise b1 + b2 overflows, the two different ways of evaluating the compound expression will give different answers.

But automatically widening the operands to int and doing the operations as int op int -> int avoids this.

于 2013-09-22T06:04:51.937 回答
0

正在发生的事情被称为“隐式扩大转换”。

当对两种类型进行操作时,较低的类型会隐式转换为较高的类型。因此_globalByte,当您尝试int使用运算符使用值 13对其进行操作时,您将使用隐式转换将其转换为 int modulus

于 2013-09-22T05:19:32.797 回答