我有一个应该是抽象的类。在其中一个抽象方法中,返回类型可能是 class1、class2 或 class3 的实例,具体取决于实现该方法的类。我想知道应该如何在抽象类中声明该方法。我考虑过使用动态类型,但我希望返回类型仅限于 3 个类之一,而不是每种类型,此外,我不确定是否可以重写它,以便在继承类中返回类型不会与抽象类中的返回类型匹配。
如果你能帮我解决这个问题,我会很高兴
Tnx!
最佳答案
看看这个:
#import <Foundation/Foundation.h>
@interface A : NSObject { }
- (A*) newItem;
- (void) hello;
@end
@interface B : A { int filler; }
- (B*) newItem;
- (void) hello;
- (void) foo;
@end
@implementation A
- (A*) newItem { NSLog(@"A newItem"); return self; }
- (void) hello { NSLog(@"hello from A"); }
@end
@implementation B
- (B*) newItem { NSLog(@"B newItem"); return self; }
- (void) hello { NSLog(@"hello from B: %d", filler); }
- (void) foo { NSLog(@"foo!"); }
@end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
A *origA = [A new];
A *myA = [origA newItem];
NSLog(@"myA: %@", myA);
B *origB = [B new];
B *myB = [origB newItem];
A *myBA = [origB newItem];
NSLog(@"myB: %@\nmyBA: %@", myB, myBA);
[origA hello];
[origB hello];
[myA hello];
[myB hello];
[myBA hello];
NSLog(@"Covariance?");
[pool drain];
return 0;
}
这是相当简洁的语法,内存管理很糟糕,但您可以看到 newItem
是虚拟的(将 newItem
发送到 myBA
返回一个B
)和协变,这似乎就是你想要的。
请注意,您还可以这样做:
B *myAB = (B*)[origA newItem];
但是返回一个A
,并且向它发送foo
会告诉您该类不响应选择器#foo
。如果省略 (B*)
转换,您将在编译时收到有关此问题的警告。
但是 ISTM 认为协方差在 Objective-C 中并不是什么大问题。
关于objective-c - "virtual"Objective-C中方法的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6842868/