【发布时间】:2012-02-04 01:13:33
【问题描述】:
首先,让我澄清一下,我知道在 Objective-C 中不能有实际的抽象类。当我说抽象时,我的意思是我没有创建该类的任何实例,而只是将其用作继承的基类。
我的抽象类包含一个 NSInteger。从这个抽象类继承的所有类都需要使用这个整数。一旦设置, NSInteger 将永远不会改变。 NSInteger 的值虽然会因派生类而异。由于它永远不会改变,我想将变量设为 const。但问题是,如果我将其设为 const,我将不得不在实例化时设置该值。因此我必须在基本抽象类中设置值 - 但是我不能根据它存在的派生类调整值。
我意识到这很难理解,所以我创建了一些基本的伪代码。我以 NSString 为例,但在我的程序中它是一个 NSInteger:
Class animal: const NSString soundItMakes = "Sound" //the constant integer
//since soundItMakes is const I have to set it upon instantiation even though it doesn't make sense in the base class
Class dog: animal //derives from animal. Needs to change the const soundItMakes to fit a dog however since it was already set in animal, the base class, I can't really change it
Class cat: animal //derives from animal. Needs to change the const soundItMakes to fit cat however since it was already set in animal, the base class, I can't really change it.
我不想从基类中删除变量,而是将它放在每个派生类中,也不想让它成为非常量。有没有人看到这个解决方案?我知道这很令人困惑,所以如果需要更多信息,请随时询问。
我在 Mac OS X Snowleopard 的 Xcode 3.2.6 中使用 Cocoa。
【问题讨论】:
-
为什么不在你的超类上定义一个只读属性,然后每个子类都可以实现getter方法来返回他们需要的东西。我认为这将是规范的 OO 方式,除非我完全错过了您的观点。
-
为什么它应该是一个变量?是什么阻止你创建一个返回它的方法?
标签: objective-c macos cocoa oop inheritance