在 Objective-C 中实现纯虚方法 [英] Implement a pure virtual method in Objective-C

查看:27
本文介绍了在 Objective-C 中实现纯虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想去那里.说真的,如何以Apple"方式实现纯虚拟方法?您是否在基类中使用协议并在这些方法上抛出异常?

I want to go to there. Seriously though, how does one implement a pure virtual method in an "Apple" way? Do you use a Protocol with your base class and throw exceptions on those methods?

推荐答案

当你在 Objective-C 中编程时,你需要清除虚拟方法之类的东西.您不会在 Objective-C 对象上调用方法,而是向它们发送消息.对象要么响应消息,要么不响应消息,但由于动态绑定,您直到运行时才能知道这一点.

When you program in Objective-C you need to purge your mind of such things as virtual methods. You don't call methods on Objective-C objects, you send messages to them. Objects either respond to messages or they don't, but due to the dynamic binding, you can't tell this until run time.

因此,您可以在基础对象上声明一个方法而不提供实现,没问题(编译器警告除外),但是当您使用此类方法直接实例化对象时,您不能让编译器标记它不会在运行时抛出错误,除非您实际将该消息发送到对象.

Thus, you can declare a method on a base object and not not provide an implementation, no problem (except for the compiler warning), but you can't have the compiler flag up when you directly instantiate an object with such methods and it won't throw an error at runtime unless you actually send that message to the object.

创建虚拟"基类的最佳方式(在我看来)是声明该方法并为其提供一个可以抛出合适异常的存根实现.

The best way to create "virtual" base classes (in my opinion) is to declare the method and give it a stub implementation that throws a suitable exception.

这篇关于在 Objective-C 中实现纯虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆