在我将[self display]消息添加到子类+display方法中之后,我得到了一个分段错误。我不明白为什么。请先分析整个代码,然后再说代码应该无限循环。添加上述消息之前的输出为:
2013-10-15 22:24:30.978 Polymorphism2[657:707] <A1: 0x7fd038c09d00>
2013-10-15 22:24:30.981 Polymorphism2[657:707] <A1: 0x7fd038c09d00>
2013-10-15 22:24:30.981 Polymorphism2[657:707] 10
2013-10-15 22:24:30.982 Polymorphism2[657:707] 60
2013-10-15 22:24:30.982 Polymorphism2[657:707] I'm not multiplying this right now
2013-10-15 22:24:30.983 Polymorphism2[657:707] Superclass!!这样就可以了。但是在添加上面的消息[self display]之后,它应该在"Superclass!!"行之前再输出一行。它应该是
2013-10-15 22:24:30.983 Polymorphism2[657:707] Subclass!!. 下面是超类的代码
@interface Abc: NSObject
- (void)calculate:(int)x;
- (void)calculate2:(int)x;
+ (void)display;
@end
@implementation Abc
- (void)calculate:(int)x{
NSLog(@"%@",self);
NSLog(@"%d",x);
[self calculate:x];
[self calculate2:x];
}
- (void)calculate2:(int)x{
NSLog(@"%d",x*10);
}
+ (void)display{
[self display];
NSLog(@"Superclass!!");
}
@end和子类的
@implementation A1
- (void)start{
NSLog(@"%@",self);
[super calculate:10];
}
- (void)calculate:(int)x{
NSLog(@"%d",x+50);
}
- (void)calculate2:(int)x{// Overriding
NSLog(@"I'm not multiplying this right now");
}
+ (void)display{
NSLog(@"Subclass");
}
- (void)callClassMethod{
[Abc display];
}
@end最后,主要的
int main(){
A1 *obj= [[A1 alloc] init]; //Subclass object
[obj start];
[obj callClassMethod];
}发布于 2013-10-16 01:22:08
如果你调用
[Abc display];if将调用Abc的+display方法,在该方法中,上下文self被解析为类Abc。
因此
[self display]被解析为
[Abc display]导致无限循环。
换句话说,如果调用[Abc display],就没有理由假定self被解析为一个子类,比如A1。
https://stackoverflow.com/questions/19386883
复制相似问题