iOS 中的虛函數的學習記錄 – iPhone手機開發技術文章 iPhone軟體開發教學課程

小明小李小王繼承Person

#import "Person.h"

@implementation Person

- (void)runAway{
    NSLog(@"run");
    return;
}

#import "xiaoming.h"
#import "Person.h"
@implementation xiaoming

- (void)runAway{
    NSLog(@"xiaoming can run 15m/s");
    return;
}

#import "xiaoli.h"

@implementation xiaoli

- (void)runAway{
    NSLog(@"xiaoli can run 12m/s");
    return;
}

#import "xiaowang.h"

@implementation xiaowang

- (void)runAway{
    NSLog(@"xiaowang can run 10m/s");
    return;
}


#import "Person.h"

@interface Teacher : NSObject

- (void)amHere:(Person *)p;

@end

#import "Teacher.h"
#import "Person.h"
@implementation Teacher

- (void)amHere:(Person *)p{
    
    NSLog(@"i am %@",[p class]);
    
    [p runAway];
    
    return;
}

@end


//OC 調用方法不看指針,看對象(地址),對象的地址調用對象的方法
    //父類的指針可以指向子類的對象,同一事件在不同的事物上,可以產生不同的結果
    
    xiaoming *ming = [[xiaoming alloc]init];
    xiaoli *li = [[xiaoli alloc]init];
    xiaowang *wang = [[xiaowang alloc]init];
    
    Teacher *t = [[Teacher alloc]init];
    
    [t amHere:ming];
    [t amHere:li];
    [t amHere:wang];

結果:

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。