Objective-c和函数中的继承

时间:2010-01-11 00:40:40

标签: objective-c inheritance polymorphism

我有一个类X,一个抽象类,以及从它继承的类A和B. A类和B类都有自己的'return_something'函数。我在其他地方有另一种方法,在一系列对象上调用'return_something',所有类型都是X.'return_something'返回不同的东西,这取决于它是A还是B,所以我可以调用id * result = [x return_something )。

我可以设计这一切都很好,但是当我来实现它时,我不知道在父类X中放什么。它需要有一个'return_something'函数才能使它可调,但函数本身是在子类中定义的。我可以在父级和两个子级中声明它,但是我没有任何东西可以从X实现返回 - 返回的对象依赖于子级的重新定义。

这对于非返回方法来说没什么问题,但是我怎么意味着在函数中使用继承和多态?

2 个答案:

答案 0 :(得分:6)

最简单的方法是从“base”函数中抛出异常。这样你就会知道它是否被错误地调用了。

其他提供明确“抽象性”的语言不需要抽象方法的方法体。

答案 1 :(得分:5)

使用objective-C协议而不是抽象基类:

@protocol ProtocolX
-(int)return_something;
@end

@interface ClassA : NSObject <ProtocolX> {
}
-init;
-(int)return_something;
@end

@interface ClassB : NSObject <ProtocolX> {
}
-init;
-(int)return_something;
@end

@implementation ClassA : NSObject <ProtocolX>
-(int)return_something { return 1; }
-init { retur [super init]; }
@end

@implementation ClassB : NSObject <ProtocolX>
-(int)return_something { return 3; }
-init { retur [super init]; }
@end

然后可以传递类型id<ProtocolX>的引用并使用:

id<ProtocolX> ref = [[ClassA alloc] init];
int myIntForA = [ref return_something];
[ref release];
ref = [[ClassB alloc] init];
int myIntForB = [ref return_something];
[ref release];