通过类名与自身调用类方法

编程入门 行业动态 更新时间:2024-10-27 08:34:26
本文介绍了通过类名与自身调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有一个名为 Calculator 的类.其中有一个类方法,称为runProgram.如果我想调用这个类的方法,在类的实现里面,这两者有什么区别:

Suppose we have a class named Calculator. There's a class method in it, called runProgram. If I wanted to call this class method, inside the class's implementation, what would the difference between these two be:

[Calculator runProgram]

[self runProgram]

这两个是一样的吗?

推荐答案

如果在实例方法中:

[self runProgram]

这里的self表示对象实例本身,因此会产生运行时错误.你要使用

in this, self means the object instance itself, and thus it will generate a runtime error. You want to use

[[self class] runProgram]

相反.

但是,如果你从另一个类方法调用这个方法,那么

However, if you call this method from another class method, then

[self runProgram]

是正确的,因为现在 self 指的是类本身.我不鼓励使用

is correct, since now self refers to the class itself. I'd discourage to use

[Calculator runProgram]

因为类的子类会错误地调用超类(Calculator)的方法,而不是可能被覆盖的方法.

because then subclasses of the class would erroneously call the superclass' (Calculator's) method instead of a possibly overridden method.

更多推荐

通过类名与自身调用类方法

本文发布于:2023-11-11 23:53:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!