【问题标题】:Segmentation Fault in objective C code目标 C 代码中的分段错误
【发布时间】:2013-10-15 17:01:30
【问题描述】:

在子类+display 方法中添加[self 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];
}

【问题讨论】:

    标签: objective-c inheritance crash segmentation-fault


    【解决方案1】:

    如果你打电话

    [Abc display];
    

    if 将调用Abc+display 方法,其中上下文self 被解析为类Abc

    因此

    [self display]
    

    被解析成

    [Abc display]
    

    导致无限循环。

    换句话说,如果您调用[Abc display],则没有理由假设self 被解析为子类,例如A1

    【讨论】:

    • 但是输出并没有反映无限循环。控制台所做的是显示输出直到“我现在没有乘以这个”,然后给出分段错误。请在你的电脑上运行这个
    • 为什么这种情况下代码会输出Segmentation Fault。它应该无限循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多