加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

oop – 2D和3D向量的适当类层次结构

发布时间:2020-12-16 09:23:42 所属栏目:安全 来源:网络整理
导读:我希望有一个通用的向量抽象类/特性来指定某些方法,例如: trait Vec { def +(v:Vec):Vec def *(d:Double):Vec def dot(v:Vec):Double def norm:Double} 我希望Vec2D和Vec3D扩展Vec: class Vec2D extends Vec { /* implementation */ }class Vec3D extends
我希望有一个通用的向量抽象类/特性来指定某些方法,例如:

trait Vec 
{
  def +(v:Vec):Vec
  def *(d:Double):Vec

  def dot(v:Vec):Double
  def norm:Double
}

我希望Vec2D和Vec3D扩展Vec:

class Vec2D extends Vec { /* implementation */ }
class Vec3D extends Vec { /* implementation */ }

但是,我怎样才能使Vec2D只能添加到其他Vec2D而不能添加到Vec3D?

现在我只是在没有普通Vec祖先的情况下实现Vec2D和Vec3D,但是重复代码会变得乏味.我必须实现两次依赖于这些类(例如Triangle,Polygon,Mesh,…)的所有几何类,一次用于Vec2D,一次用于Vec3D.

我看到java实现:javax.vecmath.Vector2d和javax.vecmath.Vector3d没有共同的祖先.这是什么原因?有没有办法在scala中克服它?

解决方法

作为 requested,设计基础性状的最有用方法涉及 CRTP和 self-type annotation.

trait Vec[T <: Vec[T]] { this: T =>
  def -(v: T): T
  def *(d: Double): T

  def dot(v: T): Double
  def norm: Double = math.sqrt(this dot this)
  def dist(v: T) = (this - v).norm
}

如果没有自我类型,则无法调用this.dot(this),因为dot需要T;因此我们需要使用注释强制执行它.

另一方面,如果没有CRTP,我们将无法在(this – v)上调用norm作为 – 返回T,因此我们需要确保我们的类型T具有此方法,例如声明T是Vec [T].

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读