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

查看:95
本文介绍了在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天全站免登陆