当前位置: 首页 > 图文教程 > 脚本技术 > Ruby > Ruby 之 class 中的 private、 protected、public

Ruby
print不自动换行,puts会自动换行
windows和linux下Ruby的下载与安装
Ruby入门点滴-Ruby的安装
Ruby入门介绍
什么是ruby和Ruby概述
RUBY文档中心-学习开始
ruby 简单例子
Ruby 字符串处理
ruby 正则表达式 教程
ruby 数组使用教程
ruby 一些简单的例子
ruby 流程控制 方法
ruby 迭代器使用方法
ruby 面向对象思维 概念
rudy 方法 分析
分析 rudy 类
rudy 继承 概念
rudy 重载方法 详解
剖析 rudy 访问控制
ruby 单态方法 分析

Ruby 之 class 中的 private、 protected、public


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 334 ::
收藏到网摘: n/a

Ruby 之 class 中的 private、 protected、public 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。