在命名空间::NodeTypes 中,我有一个类 NodeType1 和另一个类 NodeType2 的另一个对象。
我还有一个类 NetworkCollector 和另一个类 NodeType2 的另一个对象
我需要将 NodeType1 和 NodeType2 的对象作为 NetworkCollector 对象中的参数传递,并在 NetworkCollector 类中使用传递的对象的功能。
您能否建议一些可能的解决方案,如何将一个对象的引用传递给另一个类中的另一个方法。 以下示例代码不起作用:
itcl::class ::NodeTypes::NodeType1 {
private activeChannels 0;
method addChannels {numChannels} {
#set active channels
set activeChannels $numChannels
}
method getActiveChannels {} {
# return number of channels being used in the NodeType1 object
return $activeChannels
}
}
itcl::class ::NodeTypes::NodeType2 {
private activeChannels 0;
method addChannels {numChannels} {
#set active channels
set activeChannels $numChannels
}
method getActiveChannels {} {
# return number of channels being used in the NodeType2 object
return $activeChannels
}
}
::NodeTypes::NodeType2 NodeType2Object2
itcl::class ::NodeTypes:NetworkCollector {
method getTotalUsedChannels {Node1 Node2} {
set Node1Channels [Node1 getActiveChannels]
set Node2Channels [Node2 getActiveChannels]
set totalActiveChannels [$Node1Channels + $Node2Channels]
puts "Total active channels are $totalActiveChannels"
}
}
#creating objects
::NodeTypes::NodeType1 NodeType1Object
::NodeTypes::NodeType2 NodeType2Object
#adding channels to nodes
NodeType1Object::addChannels 5
NodeType2Object::addChannels 10
#calculating total active channels
::NodeTypes:NetworkCollector networkCollector1
networkCollector1 getTotalUsedChannels $NodeType1Object $NodeType2Object
问题:抛出错误----->无法读取“NodeType1Object”:没有这样的变量
您能否建议一些可能的解决方案,如何将一个对象的引用传递给另一个类中的另一个方法。
最佳答案
愚蠢的是......你的代码几乎是正确的(据我所知)。您只需要注意,在 Tcl 中添加数字是使用 expr
命令完成的,并且在读取变量时始终必须显式取消引用它们(即 $foo
确切地说是“从变量 foo
中读取值”):
set Node1Channels [$Node1 getActiveChannels]
set Node2Channels [$Node2 getActiveChannels]
set totalActiveChannels [expr {$Node1Channels + $Node2Channels}]
您也可以编写该方法,例如:
method getTotalUsedChannels {Node1 Node2} {
set numChans [$Node1 getActiveChannels]
incr numChans [$Node2 getActiveChannels]
puts "Total active channels are $numChans"
}
关于oop - 如何将一个类的 itcl 对象传递给另一个类的对象并使用所传递对象的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685619/