NS与网络模拟 第三章 示例

这几天看另一本NS2书籍《NS与网络模拟》,发现其第三章OTCL章节中的例子若使用完整的TCL文件运行时,屏幕并没有书上所描述的输出结果,弄了半天才明白书上的输出结果是通过在NS的解释环境下一行一行输入,才会有那些输出结果。
原来以为OTCL像C++一样,将所有代码行输入到一个文件,再使用NS命令执行即可!今天才发现并非如此,为了像C++那样作为一个文件运行这个例子,并能看到较为详细的输出结果,将此例子稍作了修改:
#class_example.tcl
Class Bagel  ; # 定义类Bagel
Bagel instproc init {args} { ;# Bagel类的初使化函数
  $self set toasted 0 
  puts "bagel::init{} ...."
  eval $self next $args
}
Bagel instproc toast {} {  ;# 定义Bagel类的成员函数toast
  $self instvar toasted
  incr toasted
  if {$toasted>1} then {
    puts "bagel::toast{}:something's burning!(toasted>1)"     
  } else {
    puts "bagel::toast{}:bagel's var :toasted is 0"
    }
  return {}
}
Class SpreadableBagel -superclass Bagel ;# SpreadableBagel继承于类Bagel
SpreadableBagel sBagel  ;# 生成SpreadableBagel类的对象sBagel
SpreadableBagel instproc init {args} { ;# SpreadableBagel的初使化函数
  $self set toppings {}
  puts "spreadablebagel::init{}"
  eval $self next $args    ;# 调用父类的初使化函数
}
puts "call :sBagel set toasted"
puts "\t[eval sBagel set toasted]"
# 父类Bagel的变量toasted
puts "call:sBagel toast(1st)"
puts "\t[eval sBagel toast]"  ;# 实际调用父类Bagel的toast函数"
puts "call:sBagel toast(2st)"
puts "\t[eval sBagel toast]"  ;# 实际调用父类Bagel的toast函数
puts "call:SpreadableBagel info superclass"
puts "\t[eval SpreadableBagel info superclass]"  ;# 查看父类信息
puts "call:SpreadableBagel info heritage"
puts "\t[eval SpreadableBagel info heritage]"  ;# 查看继承树信息
Bagel instproc taste {} {   ;# Bagel类增加taste函数
  $self instvar toasted
  if {$toasted == 0} then {
    return raw!
  } elseif {$toasted == 1} then {
    return toasty
  } else {
    return burnt!
  }
}
SpreadableBagel instproc spread {args} { ;
# SpreadableBagel类增加spead函数
  $self instvar toppings
  set toppings [concat $toppings $args]
  return $toppings
}
SpreadableBagel instproc taste {} { 
# SpreadableBagel类增加taste函数
  $self instvar toppings
  set t [$self next]     
  # $self next 调用父类Bagel的taste函数
  foreach i $toppings {
    lappend t $i     
    # 在变量$t后增加$i的值
  }
  return $t
}
Class Sesame  ;# 定义类Sesame
Sesame instproc taste {} {
  concat [$self next] "sesame"
}
Class Onion
Onion instproc taste {} {
  concat [$self next] "onion"
}
Class SesameOnionBagel -superclass {Sesame Onion SpreadableBagel} 
puts "call:SesameOnionBagel info heritage"
puts "\t[eval SesameOnionBagel info heritage]" ;# 查看SesameOnionBagel类的继承树信息
puts "call:SesameOnionBagel abagel -spread butter"
puts "\t[eval SesameOnionBagel abagel -spread butter]"
# 调用spead函数,来自SpreadableBagel类
puts "call:abagel taste"
puts "\t[eval abagel taste]"
 

你可能感兴趣的:(继承,职场,休闲,ns2,OTCL)