首页 > 解决方案 > Tcl:添加实例类的不同方式之间的区别

问题描述

我找到了两种实例类的方法:

一个是:

class_name create instance
instance class_method

另一个是:

set instance [class_name new]
$instance class_method

每种方式都运作良好,那么两种方式之间有什么区别吗?

标签: tcl

解决方案


我尝试过一些案例,

类定义如下:

oo::class create class_name {
    variable text
    method add {t} { set text $t }
    method print { } { puts $text }
}

第一种方式:

class_name create foo
foo add "abc"
foo print

class_name create foo

它将返回:

abc
Error: can't create object "foo": command already exists with that name

第二种方式:

set foo [class_name new]
$foo add "abc"
$foo print

set foo [class_name new]
$foo add "def"
$foo print

它将返回:

abc
def

这是我发现的一个区别,似乎第二种方式更方便。

还是期待师父提供权威的答案或文件。


推荐阅读