标签:
#import <Foundation/Foundation.h> @protocol Add <NSObject> - (int)addA:(int)a b:(int)b; @end #import <Foundation/Foundation.h> @protocol Sub <NSObject> - (int)subA:(int)a b:(int)b; @end #import <Foundation/Foundation.h> @protocol Mul <NSObject> - (int)mulA:(int)a b:(int)b; @end ==================================================以上是三个协议 下面是新建一个继承与NSObject的计算类Calculator #import <Foundation/Foundation.h> #import "Add.h" #import "Sub.h" #import "Mul.h" //遵守多个协议 //类似于c++的多继承 @interface Calculator : NSObject <Add,Sub,Mul> @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 <Foundation/Foundation.h> #import "Calculator.h" /* 现在有多个类,一个是加法器类(会算加法) 第二个类是减法器类(减法功能)第三个乘法器类(乘法) 实现一个类分别可以进行+- c++可以用多继承实现 但是OC没有多继承 但是OC可以通过协议来实现 */ 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; }
标签:
原文地址:http://my.oschina.net/u/2410306/blog/522755