2

我正在尝试理解以下类中的 add 方法,该方法取自《Scala 编程 - 第二版》一书。这是否正确:“add”方法定义了一个 Rational 类型的运算符。我不知道新 Rational 中发生了什么:

numer * that.denom + that.numer * denom,
denom * that.denom

numer 和 denom 是如何在这里分配的?, 为什么每个表达式用逗号分隔?全班:

class Rational(n: Int , d: Int) {

  require(d != 0)

  private val g = gcd(n.abs, d.abs)
  val numer = n / g
  val denom = d/ g

  def this(n: Int) = this(n, 1)

  def add(that: Rational): Rational = 
    new Rational(
        numer * that.denom + that.numer * denom,
        denom * that.denom
        )

  override def toString = numer +"/" + denom

  private def gcd(a: Int, b: Int): Int = 
    if(b == 0) a else gcd(b, a % b)
}
4

1 回答 1

4

这两个表达式是Rational构造函数的参数,因此它们将分别是private valsnd。例如

class C(a: Int, b: Int)
val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention

add方法实现有理数加法:

 a     c     a*d     c*b     a*d + c*b
--- + --- = ----- + ----- = -----------
 b     d     b*d     b*d        b*d

在哪里

 a = numer
 b = denom
 c = that.numer
 d = that.denom
于 2012-09-13T21:56:27.550 回答