国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 新巴尔虎左旗| 重庆市| 通河县| 枣阳市| 云阳县| 湖州市| 武夷山市| 大关县| 江达县| 沈阳市| 周宁县| 德江县| 西林县| 乡城县| 深泽县| 璧山县| 桐乡市| 衡山县| 密山市| 板桥市| 蒙阴县| 新闻| 封开县| 武义县| 比如县| 霍林郭勒市| 泗水县| 巴林左旗| 宝坻区| 大港区| 汝南县| 徐汇区| 武陟县| 土默特左旗| 富源县| 杨浦区| 阿拉善右旗| 贵南县| 蓬莱市| 阿巴嘎旗| 望江县|