Re: [問題] 請教關於 static method

看板Ruby作者 (godfat 真常)時間17年前 (2008/02/14 01:05), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串3/3 (看更多)
: 推 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://www.ptt.cc/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

02/14 22:21, , 1F
文章代碼(AID): #17ioD9_F (Ruby)
文章代碼(AID): #17ioD9_F (Ruby)