国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 西青区| 东辽县| 闻喜县| 千阳县| 大英县| 玛多县| 宜都市| 富锦市| 高雄市| 同江市| 武鸣县| 扶沟县| 庆城县| 安阳县| 清水河县| 平定县| 芒康县| 建水县| 东乌珠穆沁旗| 印江| 峨山| 扶沟县| 遂平县| 甘德县| 隆安县| 彭阳县| 瑞丽市| 通渭县| 勐海县| 四子王旗| 边坝县| 新邵县| 横峰县| 禹城市| 邛崃市| 台南县| 邵东县| 灵山县| 久治县| 昆山市| 綦江县|