C++ 相当于什么? Objective-C 中的纯虚函数?

发布于 2024-10-06 13:04:42 字数 142 浏览 5 评论 0原文

简单的答案是协议。

还有一点就是据说ObjectC中的所有方法都是virtual的,所以ObjC中就不用说virtual了。

我觉得很难理解这个概念。

有什么评论可以更清楚地解决这个问题吗?

感谢您的评论。

Simple answer would be Protocol.

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 ?

Thanks for commenting.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北笙凉宸 2024-10-13 13:04:42

简单的答案是协议。

简单但错误。协议是一种接口规范。它是对象必须响应的消息集合(暂时忽略 @optional 关键字)。

术语“虚拟函数”在 Objective-C 中没有直接对应的术语。在 Objective-C 中,您不对对象调用函数,而是向它们发送消息。然后,对象本身决定如何响应消息,通常是通过在其类对象中查找消息,找到关联的方法并调用它。请注意,这一切都发生在运行时,而不是编译时。

消息(或“选择器”,为其提供技术术语)和方法之间的映射完全由 @implementation 构建。 @interface 中的方法声明只是为了向编译器提供所需的信息,以警告您可能已经忘记了方法实现。它只是一个警告,因为直到运行时你才能知道该对象是否真的响应该消息。例如,其他人可以向现有类添加一个类别,为缺少的方法提供实现,或者一个类可以重写 forwardingTargetForSelector: 以转发它在其他地方不响应的消息。

Simple answer would be Protocol.

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.

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.

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.

弃爱 2024-10-13 13:04:42

Objective-C 中对象的方法不是虚函数,而是实函数。

我不敢苟同,Obj-C 中的方法并不像人们想象的那样真实。它们的行为就像 C++ 中的虚函数一样,只是你不能在 Objective-C 中创建“纯虚”函数。

干杯,
拉克西特

Methods on objects in Objective-C are not virtual functions, they are real functions.

I beg to differ, methods in Obj-C aren't quite real like one would expect. They behave just like virtual functions in C++ do, except you cannot make a 'pure virtual' function in Objective-C.

Cheers,
Raxit

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文