作者godfat (godfat 真常)
看板Ruby
标题Re: [问题] 请教关於 static method
时间Thu Feb 14 01:05:11 2008
: 推 mokuku:原来要叫 class method 喔! 02/14 00
在 c++ 会叫 static method 的原因,大抵上是为了节省 keyword,
只要让一个 keyword 有两种以上的功能,就能够减少名称污染。
在 c 里,static 大致上是使得被修饰者的 scope 限定在某个范围,
如果加在某个 global function/variable 上,表示这样东西的 scope
只在这个 compilation unit 中(.c 档)。如果是在某个 function 中的
variable 上,则表示这个 variable 只被这个 function 所见。
在 c++ 里,把 static 的概念延伸,放到 class function(method) 中,
表示这个 function/method 只被这个 class 所见,同时,static method
无法被 override, 也就是不能成为 virtual function, 也就是 name binding
会是 static 的,compile time 即决定被呼叫的 function 是谁。
这还算有点道理...。
java 会叫 static method 的原因,我看最大的原因是为了跟 c++ 一致。
但是 java 已经没有 c/c++ 的 static variable, 也没有 static global variable,
这个 static 字眼就有一点点奇怪了。不过他仍然是 static binding,
也就是同样无法被 override, 所以大概还勉强说得过去吧。
而在 ruby 中,method call 其实只有一种,class method 其实也是
class instance 的 instance method, 所以他也能够被 override,
动态改变被呼叫的 method, 这样叫 static 就很说不过去了。
: → mokuku:我用你的 code 测试的结果跟你一样, class method 比较慢! 02/14 00
在我的电脑上,呼叫一百万次才差 0.02 秒,没差吧 @_@
明年可能就是一千万次才差 0.02 秒了...
--
#!/usr/bin/env ruby [露比] /Programming (Kn|N)ight/ 看板《Ruby》
# if a
dog nailed
extra legs that
http://webptt.com/cn.aspx?n=bbs/Ruby/index.html
#
walks like an octopus, and Welcome ~
Ruby@ptt~
#
talks like an octopus, then
◢█◣ http://www.ruby-lang.org/
# we are happy to treat it as
█ http://www.ruby-doc.org/
# if it were
an octopus.
◥ ◤ http://www.rubyforge.org/
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.135.28.18