标签:
在Nim中,proc 是定义过程的关键字,method 是定义方法的关键字。它们之间根本的区别是proc定义的过程是静态绑定,method定义的方法是动态绑定。谈到静态绑定、动态绑定又会提到重载、重写和多态等方面的内容,如果对上述的一些概念不太理解,可以看我的上一篇博文。
过程的重载:
proc print (): void =
echo ("This is empty")
proc print (a:int): void =
echo ("int a = ",a)
proc print (a:float): void =
echo ("float a = ",a)
print()
print(1)
print(1.0)Out: This is empty int a = 1 float a = 1.0
proc定义的过程重载时可以在类中,也可以不在类中。而method定义的方法则只能在类内部重载。我想这应该和proc是静态绑定,而method是动态绑定有关。
方法的重载:
type
Thing = ref object of RootObj
Unit = ref object of Thing
x: int
method collide(a, b: Thing) {.inline.} =
quit "to override!"
method collide(a: Thing, b: Unit) {.inline.} =
echo "1"
method collide(a: Unit, b: Thing) {.inline.} =
echo "2"
method collide(a: Unit, b: Unit) {.inline.} =
echo "3"
var a, b: Unit
var c: Thing
new a
new b
new c
collide(a, c) # output: 2
collide(a, b) # output: 3
类中如果proc定义的过程重载,则过程调用时,由于proc是静态绑定,所以严格按照过程参数要求调用,如果参数类型不匹配编译时会出错。如果是method定义的方法是,由于method是动态绑定,运行时会从左向右匹配参数类型,以确定调用哪个方法。如上例,如果把第四个collide方法注释掉,则调用collide(a,b)会输出2。
重写与多态:
#Module: tProcMethod.nim
type Animal* = ref object of RootObj
name*: string
age*: int
proc SelfIntroduce*(this: Animal): void = echo ("my name is animal")
method vocalize*(this: Animal): string = "..."
method ageHumanYrs*(this: Animal): int = this.age
type Dog* = ref object of Animal
proc SelfIntroduce*(this: Dog): void = echo ("my name is ",this.name)
method vocalize*(this: Dog): string = "woof"
method ageHumanYrs*(this: Dog): int = this.age * 7
type Cat* = ref object of Animal
proc SelfIntroduce*(this: Cat): void = echo ("my name is ",this.name)
method vocalize*(this: Cat): string = "meow"#Module:testProcMethod.nim
import tProcMethod
var animals : Animal
animals = Dog(name: "Sparky", age: 10)
echo animals.name
echo animals.age
echo animals.vocalize() #method方法调用,是通过 实例对象引用.方法名
echo animals.ageHumanYrs()
tProcMethod.SelfIntroduce(animals) #这里调用proc过程是用 模块名.过程名,在在Windows下用命令行运行文件时,文件名(模块名)的所有字母被认为是小写,
#这里调用过程时要注意模块名字母的大小写。在Linux下则区分大小写。
animals = Cat(name: "Mitten", age: 10)
echo animals.vocalize()
echo animals.ageHumanYrs()
tProcMethod.SelfIntroduce(animals)Out: Sparky 10 woof 70 my name is animal neow 10 my name is animal
总结:
1、过程是静态绑定,方法是动态绑定
2、过程和方法都能重载,只不过方法只能在类的内部。
3、过程像是Java中的静态方法,不能被重写,也就不具有多态性。
4、要实现多态性,类中的操作得是method定义的方法。
5、过程是通过 模块名.过程名 调用,方法是通过 实例对象的引用.方法名 调用。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/dajiadexiaocao/article/details/46912605