Private
private 函數只能 在本類和子類的 上下文中調用,且只能通過self訪問。
這個意思就是:private函數,只能在本對象內部訪問到。
對象實例變量(@)的訪問權限就是 private。
復制代碼 代碼如下:
class AccessTest
def test
return “test private”
end
def test_other(other)
“other object ”+ other.test
end
end
t1 = AccessTest.new
t2 = AccessTest.new
p t1.test # => test private
p t1.test_other(t2) # => other object test private
# Now make 'test' private
class AccessTest
private :test
end
p t1.test_other(t2) #錯誤 in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)
Protected
protect 函數只能 在本類和子類的 上下文中調用,但可以使用 other_object.function的形式。(這跟 C++ 的 private 模式等同)
這個的關鍵是 protected函數可以在同類(含子類)的其它對象的內部中使用。
# Now make 'test' protect
class AccessTest
protected:test
end
p t1.test_other(t2) # other object test private
Public
public 函數可以在任何地方調用。成員函數和常量的默認訪問權限就是public。