问题描述
简单的答案将是协议。
另一点是,据说ObjectC中的所有方法都是虚拟的,所以不需要在ObjC中说虚拟。
The another point is that it is said that all methods in ObjectC are virtual, so no need to say virtual in ObjC.
我很难理解这个概念。
I find it hard to understand this concept.
任何意见,以解决这个问题更清楚?
Any comments to figure out more clear around this question ?
感谢您的评论。
推荐答案
简单但错误。协议是接口规范。它是一个对象必须(忽略现在的 @optional
关键字)响应的消息的集合。
Simple but wrong. A protocol is an interface specification. It's a collection of messages that an object must (ignoring the @optional
keyword for now) respond to.
术语虚拟函数在Objective-C中没有直接对应的。在Objective-C中,不要调用对象的函数,而是向它们发送消息。对象本身然后决定如何响应消息,通常通过查找其类对象中的消息,找到相关联的方法并调用它。注意这一切都发生在运行时,而不是编译时。
The term "virtual function" has no direct counterpart in Objective-C. In Objective-C you don't call functions on objects, you send messages to them. The object itself then decides how to respond to the message, typically by looking up the message in its class object, finding the associated method and invoking it. Note that this all happens at run time, not compile time.
消息(或选择器给他们的技术术语)和方法之间的映射完全是从 @implementation
。 @interface
中的方法声明只是为了给编译器提供所需的信息,警告您可能已经忘记了一个方法实现。它只是一个警告,因为你不能告诉,直到运行时,对象是否真的响应消息或不。例如,其他人可以向现有类添加一个类别,为缺失的方法提供实现,或者类可以覆盖 forwardingTargetForSelector:
,以转发不会响应其他地方的邮件。
The mapping between messages (or "selectors" to give them their technical term) and methods is built entirely from the @implementation
. The method declarations in the @interface
are only there to give the compiler the information it needs to warn you that you may have forgotten a method implementation. And it is only a warning because you can't tell until run time whether whether the object really does respond to the message or not. For example, somebody else could add a category to an existing class that provides implementations for missing methods, or a class could override forwardingTargetForSelector:
to forward messages it doesn't respond to elsewhere.
这篇关于什么是Objective-C中的C ++纯虚函数的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!