object C—类中函数的调用

本文通过创建三个继承关系的 Objective-C 类并调用同名方法,演示了方法解析的过程。展示了如何根据对象的实际类型来确定方法的具体实现。

Object C—类中函数的调用

创建,三个类。然后,在代码中调用相同名字的函数。观察他们的调用次序。

@interface test : NSObject
- (void)print;
@end

@implementation test
- (void)print{
    NSLog(@"test0");
}
@end


@interface test1 : test
- (void)print;
@end

@implementation test1
- (void)print{
    NSLog(@"test1");
}
@end


@interface test2 : test
- (void)print;
@end

@implementation test2
- (void)print{
    NSLog(@"test2");
}
@end

我们创建了三个类,然后在下面使用。

    test1 *test11 = [[test1 alloc] init];
    [test11 print];
    test2 *test22 = [[test2 alloc] init];
    [test22 print];

    test *test00;
    test00 = test11;
    [test00 print];

输出结果:

2015-05-22 14:00:41.858 test[1034:75692] test0

2015-05-22 14:00:41.858 test[1034:75692] test2

2015-05-22 14:00:41.858 test[1034:75692] test0

总结:在函数预编译的时候,test00认为调用print函数为test类申明中的函数,但是在真正编译的时候,发现这个test00指针指向了一个test11(test1类的实例),因此,按照函数方法从子类向父类搜索的性质来看,这个方法调用的是test1中的实现方法。

转载于:https://www.cnblogs.com/AbeDay/p/5026924.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值