14. Objective-C 泛型的协变与逆变
@interface Base : NSObject
@end
@implementation Base
@end
@interface Sub : Base
@end
@implementation Sub
@end
@interface Queue<ObjectType> : NSObject
- (void)enqueue:(ObjectType)value;
- (ObjectType)dequeue;
@end
@implementation Queue
- (void)enqueue:(__unused id)value {}
- (id)dequeue { return nil; }
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Queue<Sub *> *subQueue = [[Queue alloc] init];
Queue<Base *> *queue = subQueue; // Warning: Incompatible pointer types initializing 'Queue<Base *>' with an expression of type 'Queue<Sub *>'
[queue enqueue:[Sub new]];
}
return 0;
}参考链接
Last updated
Was this helpful?