国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Ruby > 正文

Ruby 之 class 中的 private、 protected、public

2020-10-29 19:46:29
字體:
供稿:網(wǎng)友
Private
private 函數(shù)只能 在本類和子類的 上下文中調(diào)用,且只能通過self訪問。

這個意思就是:private函數(shù),只能在本對象內(nèi)部訪問到。

對象實例變量(@)的訪問權(quán)限就是 private。
復(fù)制代碼 代碼如下:

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 函數(shù)只能 在本類和子類的 上下文中調(diào)用,但可以使用 other_object.function的形式。(這跟 C++ 的 private 模式等同)

這個的關(guān)鍵是 protected函數(shù)可以在同類(含子類)的其它對象的內(nèi)部中使用。

# Now make 'test' protect

class AccessTest
protected:test
end

p t1.test_other(t2) # other object test private

Public
public 函數(shù)可以在任何地方調(diào)用。成員函數(shù)和常量的默認訪問權(quán)限就是public。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 搜索| 岗巴县| 什邡市| 新郑市| 华亭县| 贡觉县| 商河县| 洪江市| 武山县| 道孚县| 江山市| 吴旗县| 鲜城| 邯郸市| 延寿县| 康乐县| 咸宁市| 湖南省| 汽车| 新蔡县| 景谷| 枣庄市| 沙坪坝区| 沛县| 义马市| 江孜县| 荆门市| 洞口县| 云和县| 五大连池市| 福安市| 灵山县| 甘谷县| 宁海县| 闸北区| 常宁市| 巫溪县| 大英县| 黄陵县| 峨眉山市| 龙陵县|