使用伴随对象时的方法名称限定 [英] method name qualification when using a companion object

查看:81
本文介绍了使用伴随对象时的方法名称限定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Scala.我创建了一个伴随对象(请参见下面的代码片段),其中定义了一个运算符^(代表复杂的共轭).我必须使用关联类中的伴随对象名称来限定它.我的印象是我应该无限制地使用同伴的方法.有人可以告诉我我做错了什么吗?

I am just learning Scala. I created a companion object (see code snippet below) where I define an operator, ^, (to represent complex conjugation). I have to qualify it with the companion objects name inside the associated class. I was under the impression that I should have unqualified access to the methods of the companion. Can someone tell me if I have done something wrong?

class CQ(val r: Q, val i:Q) {

  def +(z : CQ): CQ = {
    return new CQ(r + z.r, i + z.i)
  }

  def -(z: CQ): CQ = {
    return new CQ(r - z.r, i-z.i)
  }

  def *(z: CQ): CQ = {
    return new CQ(r*z.r - i*z.i, r*z.i + i*z.r)
  }

  def /(z: CQ): CQ = {
    val d = z.r * z.r + z.i * z.i
    val n = this * CQ.^(z) // that I needed to qualify "^" is what I don't get
    return new CQ(n.r / d, n.i /d)
  }

  override def toString = r + " + " + i + "i"
}
object CQ {

  def ^(z : CQ) : CQ = {
    return new CQ(z.r, Q.NEGONE*z.i)
  }

  val ONE = new CQ(Q.ONE,Q.ZERO)
  val ZERO = new CQ(Q.ZERO, Q.ZERO)
  val I = new CQ(Q.ZERO, Q.ONE)
  val NEGONE = I * I
}

注意:这里有另一个类Q,正在使用中,但未列出.

NOTE: there is another class, Q, that is being used here but is not listed.

推荐答案

对象和类的成员位于不同的范围内,不会自动导入到同伴中.因此,是的,您需要使用合格的访问权限或导入所需的成员.

The members of the object and the class are in different scopes and are not imported automatically into the companion. So yes, you either need to use qualified access or import the member you need.

您可能将其与私有访问权相混淆:您可以访问同伴的私有成员(但只能通过合格访问权或在导入之后).

You might be confusing this with private access: you can access the private members of the companion (but only by qualified access or after importing).

这篇关于使用伴随对象时的方法名称限定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆