我正在尝试使用itcl创建一些对象,然后将它们存储在数据结构中,以便我以后可以调用它们的方法。但它给出了一个错误:
以下是我写的代码:
itcl::class router {
variable name;
variable mac;
variable interface_list;
variable topology;
constructor {rname rmac rtopology} {
puts "creating new router $rname / $rmac within [$rtopology get_name]"
set name $rname;
set mac $rmac;
set topology $rtopology;
}
destructor {
delete $this;
}
method add_interface {name network_id} {
set int [interface #auto $name $network_id $this];
lappend interface_list $int;
}
method get_interfaces {} {
return $interface_list;
}
method get_name{} {
return $name;
}
method get_mac{} {
return $mac;
}
method get_topology {} {
return $topology;
}
}
itcl::class topology {
variable name;
variable router_list;
constructor {tname} {
set name $tname;
set router_list [dict create];
}
method add_router {name mac} {
set newrouter [router #auto $name $mac $this];
dict set router_list $name $newrouter;
}
method add_routerinterface {rname iname networkid} {
foreach r [dict keys $router_list] {
if {[$r get_name] == rname} {
$r add_interface $iname $networkid;
break;
}
}
}
method get_name {} {
return $name;
}
method get_routers {} {
return $router_list;
}
method show {} {
foreach rkey $router_list {
set router [dict get $router_list $rkey];
set rname [$router get_name];
}
}
}
topology t "JitixNet";
t add_router R1 fwe2165;
t add_router R2 dagsyu2;
t add_router R3 fasdjg3;
t show;
错误如下:
D:\Tcl\code>tclsh network-topology.tcl creating new router R1 / fwe2165 within JitixNet creating new router R2 / dagsyu2 within JitixNet creating new router R3 / fasdjg3 within JitixNet bad option "get_name": should be one of... router0 add_interface name network_id router0 cget -option router0 configure ?-option? ?value -option value...? router0 get_interfaces router0 get_mac{} return $mac; router0 get_name{} return $name; router0 get_topology router0 isa className while executing "$router get_name" (object "::t" method "::topology::show" body line 4) invoked from within "t show" (file "network-topology.tcl" line 142)
有人可以帮忙吗?我在我的智慧结束......坦率地说,我期待ITcl与Java类似......
答案 0 :(得分:3)
问题是您需要在方法名称和(空)参数列表之间放置一个空格。对于Tcl中的命令,这是正常的(如果声明标准Tcl过程,则必须执行相同的操作)。
如果您查看错误消息,您可以看到“允许的调用方式”之一是:
get_name{} return $name;
这是一个非常奇数名称和一组明显奇怪的参数。快速浏览一下代码就可以确认缺少空间。 (这不是一个错误,因为ITcl如何处理部分声明的特殊性。我并不特别关心这一点,但那是偏离主题......)