NS by Example 笔记(1)OTcl: The User Language

原教材地址 http://nile.wpi.edu/NS/ 读过原文的笔记,写成中文以后也便于理解。并没有100%对原文逐字翻译,所以有歧义的地方还需要参考原文。

 

OTcl: The User Language

 

基本上, ns是一个带有模拟对象库的OTcl解释器。

 

例题1:如何建立procedure 并运行, 变量赋值,for循环。

 

OTcl 是具有面向对象的 Tcl 语言,就像C 和 C++ 的关系一样.

运行脚本, 把代码保存到 ex-tcl.tcl 文件。 然后在命令行下输入"ns ex-tcl.tcl" 或者 "tcl ex-tcl.tcl"

 

# Writing a procedure called "test"
proc test {} {
    set a 43
    set b 27
    set c [expr $a + $b]
    set d [expr [expr $a - $b] * $c]
    for {set k 0} {$k < 10} {incr k} {
	if {$k < 5} {
	    puts "k < 5, pow = [expr pow($d, $k)]"
	} else {
	    puts "k >= 5, mod = [expr $d % $k]"
	}
    }
}

# Calling the "test" procedure created above
test

 

在 Tcl 中,

关键字 proc 去定义一个 procedure, 后边加上 procedure 名和大括号中加入需要的参数(arguments)。

关键字 set 用来给变量赋值。 [expr ...] 让解释器去计算 expr 之后的表达式的结果。

关键字 $ 用得到变量的值。

关键字 puts 打印双引号中的字符串。

 

结果为



 

 

 

 

 

例题2:OTcl中面向对象编程

 

解释了如何建立和使用对象。因为ns中无论ns对象是否是用C++编写还是用OTcl影像,本质上都是OTcl对象

 

 

# Create a class call "mom" and 
# add a member function call "greet"
Class mom
mom instproc greet {} {
    $self instvar age_
    puts "$age_ years old mom say:
    How are you doing?"
}

# Create a child class of "mom" called "kid" 
# and overide the member function "greet"
Class kid -superclass mom
kid instproc greet {} {
    $self instvar age_
    puts "$age_ years old kid say:
    What's up, dude?"
}

# Create a mom and a kid object set each age
set a [new mom]
$a set age_ 45
set b [new kid]
$b set age_ 15

# Calling member function "greet" of each object
$a greet
$b greet

 

 

 例子定义2个对象, "mom" 和 "kid"。"kid" 是 "mom" 的子类, 并且分别给这两个类定义一个名叫"greet"的成员函数(member function)。  类定义好后我们个每个类声明一个实例,分别是 a 和 b。然后分别把 a 和 b 的 "age" 变量赋值为45 和 15。最后调用这两个实例的 "greet" 函数

 

关键字 Class 新建对象的类

关键字 instproc 给类定义一个成员函数member function

关键字 -superclass 类的继承关系 

关键字 $self 和 C++中 "this" 指针相似

关键字 instvar 检查变量名是否已经在这个类或者他的父类中声明, 如果已经声明的话则直接引用,否则声明一个新的

关键字 new 新建一个对象类的实例

 

运行方法相信大家都知道了,输出的给过应该是:

                                                                  45 years old mum say:

                                                                  How are you doing?

                                                                  15 years old kid say:

                                                                  What's up, dude (怎么这样和你老妈说话啊, 呵呵)

你可能感兴趣的:(编程,C++,c,C#,Tcl)