[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]
行の直前にもう 1 行出力する必要があります"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];
}