这是我的第一堂课,我的方向对吗?我问自己的问题主要是关于我的init()方法。还好吗?我不确定…我在寻求一些建议,method…
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]
发布于 2018-09-06 03:22:57
使用构造函数可能比使用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),但请注意,您不需要在表达式的大括号内转义行尾(因为行尾已经用大括号转义)。
https://stackoverflow.com/questions/52191453
复制相似问题