Objective-c能实现多层继承吗?

答案是不行的。OC不支持多层继承,但可以通过遵守多个协议实现多继承。

#import 

@protocol Add 
- (int)addA:(int)a b:(int)b;
@end

#import 

@protocol Sub 
- (int)subA:(int)a b:(int)b;
@end


#import 

@protocol Mul 
- (int)mulA:(int)a b:(int)b;
@end
==================================================以上是三个协议
下面是新建一个继承与NSObject的计算类Calculator
#import 
#import "Add.h"
#import "Sub.h"
#import "Mul.h"

//遵守多个协议
//类似于c++的多继承
@interface Calculator : NSObject 

@end

#import "Calculator.h"

@implementation Calculator
- (int)addA:(int)a b:(int)b {
    return a+b;
}
- (int)subA:(int)a b:(int)b {
    return a-b;
}
- (int)mulA:(int)a b:(int)b {
    return a*b;
}
@end
==========================================
#import 
#import "Calculator.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Calculator *calc = [[Calculator alloc] init];
        
        NSLog(@"%d",[calc addA:1 b:1]);//2
        NSLog(@"%d",[calc subA:1 b:1]);//0
        NSLog(@"%d",[calc mulA:1 b:1]);//1
    }
    return 0;
}

你可能感兴趣的:(Objective-c能实现多层继承吗?)