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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Ruby 之 class 中的 private、 protected、public

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

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

對象實例變量(@)的訪問權(quán)限就是 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 函數(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ā)表
主站蜘蛛池模板: 应用必备| 浮山县| 平泉县| 长治县| 东方市| 东明县| 会昌县| 屯门区| 万源市| 塔河县| 枣庄市| 盐山县| 牡丹江市| 巫溪县| 武强县| 鄄城县| 社会| 河曲县| 桐柏县| 南澳县| 驻马店市| 海口市| 江安县| 新源县| 康乐县| 茶陵县| 德阳市| 夹江县| 蕲春县| 横峰县| 平阴县| 平陆县| 合川市| 吴江市| 合阳县| 平安县| 正宁县| 全州县| 广昌县| 阳曲县| 靖远县|