TclOO:Class Point

问题描述 投票:0回答:1

这是我的第一堂课,我正朝着正确的方向前进?我问自己主要是关于我的init()方法的问题。没关系 ?我不确定......我正在寻找一些建议,方法......

oo::class create Point {

    variable x y z

    method init {val} {
        lassign $val x y z
    }

    method x {} {
        set x $x
    }

    method y {} {
        set y $y
    }

    method z {} {
        set z $z
    }

    method formatPoint {} {
        set x [format %.4f $x]
        set y [format %.4f $y]
        set z [format %.4f $z]
    }

}
proc distance3D {a b} {

    return [expr { \
            sqrt(([$a x] - [$b x])**2 \
               + ([$a y] - [$b y])**2 \
               + ([$a z] - [$b z])**2 )}]
}

set P0 [Point new]
set P1 [Point new]

$P0 init {8.2 30 40}
$P1 init {9.5 10 10}
set val [distance3D $P0 $P1]
class tcl
1个回答
2
投票

拥有构造函数而不是init方法可能会更好:

constructor val {
    lassign $val x y z
}

set P0 [Point new {8.2 30 40}]

要么

constructor args {
    lassign $args x y z
}

set P0 [Point new 8.2 30 40]

OOP方面,没有坐标的点没有多大意义,你可能不想通过改变坐标来“移动”点,所以在创建点时应该分配坐标,并用新的点替换点一个如果拥有该点的东西移动。

通过formatPoint方法更改坐标值是个好主意吗?为什么不让坐标保持其值并提供格式化访问:

method formatPoint {} {
    format {%.4f %.4f %.4f} $x $y $z
}

坐标访问方法有点偏。尝试

method x {} {
    set x
}

相反:set的一元形式返回值。要么

method x {} {
    return $x
}

如果你更喜欢。

计算得到正确的结果(~36.0789),但请注意,您不需要在表达式的大括号内转义行结尾(因为行结尾已被大括号转义)。

© www.soinside.com 2019 - 2024. All rights reserved.