gpt4 book ai didi

language-agnostic - 是否存在具有基于对象访问级别的语言?

转载 作者:行者123 更新时间:2023-12-04 08:57:51 25 4
gpt4 key购买 nike

关于 Java、C#、C++ 和 PHP 中访问级别的一个常见误解是它适用于对象而不是类。也就是说,(比如说)X 类的一个对象不能看到另一个 X 的私有(private)成员。事实上,当然,访问级别是基于类的,一个 X 对象可以毫不费力地引用另一个对象的私有(private)成员。

是否存在具有基于对象访问级别的语言?它们是替代或补充基于类的访问吗?这个特性对程序设计有什么影响?

最佳答案

Ruby 具有基于对象的访问级别。这是来自 Programming Ruby 的引用:

The difference between "protected" and "private" is fairly subtle, and is different in Ruby than in most common OO languages. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object---it is never possible to access another object's private methods directly, even if the object is of the same class as the caller.



来源: http://whytheluckystiff.net/ruby/pickaxe/html/tut_classes.html#S4

Java 和 Ruby 之间的示例差异

java
public class Main {
public static void main(String[] args) {
Main.A a1 = new A();
Main.A a2 = new A();

System.out.println(a1.foo(a2));
}

static class A
{
public String foo(A other_a)
{
return other_a.bar();
}

private String bar()
{
return "bar is private";
}
}
}

// Outputs
// "bar is private"

ruby
class A
def foo other_a
other_a.bar
end

private
def bar
"bar is private"
end
end

a1 = A.new
a2 = A.new

puts a1.foo(a2)

# outputs something like
# in `foo': private method `bar' called for #<A:0x2ce9f44> (NoMethodError)

关于language-agnostic - 是否存在具有基于对象访问级别的语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1233375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com