为什么 pascal 禁止方法的参数和类的数据成员使用相同的标识符名称?
type
TPerson = class(TObject)
name : string;
constructor create(name : string);
end;
会触发编译器错误。
我认为 self 或 this 指针/引用就足够清晰了。那么,这样做有什么好处呢?
编辑:还有一个问题,您能否说明部署此策略的其他语言是什么?
type
TPerson = class(TObject)
name : string;
constructor create(name : string);
end;
would trigger compiler error.
I think a self
or this
pointer/reference is good enough,for its clarity. So, what are the advantages of doing so?
EDIT: One more question, could you show what are the other languages that deploy this policy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了防止参数名称会遮盖类成员的名称冲突。事情不可能这样发生,而且每个名字都是明确的。
请记住,Pascal 是一种束缚和纪律语言;这些旨在防止常见错误。
防止出现问题的另一个选择是 Python 所做的:使用
this
或self
强制实例成员的资格,以便您必须为每个添加前缀使用self
访问实例成员。不过,我不知道还有其他语言有这种限制。但有些语言特性确实是独一无二的;例如,受检查的异常也是如此。
To prevent name clashes where the parameter name would shadow the class member. It just can't happen this way and every name is unambiguous.
Remember that Pascal is a bondage-and-discipline language; those are designed to try to prevent common errors.
Another option to prevent the perceived problem is what Python does: mandate the qualification of instance members with
this
orself
so that you have to prefix every instance member access withself
.I don't know of any other language with that restriction, though. But some language features are indeed unique; checked exceptions for example are, too.