Objective-C的分类和协议
#import <Foundation/Foundation.h> //define the Fraction class @interface Fraction : NSObject { //声明实例变量 int numerator; int denominator; } //将实例变量转换为属性 @property int numerator,denominator; //定义实例方法 -(void) setTo: (int) n over: (int) d; -(Fraction *) add: (Fraction *) fraction; -(void) reduce; -(double) convertToNumber; -(void) print; @end;
然后,从接口部分删除add:方法,并将其添加到新分类,同时添加其他三种要实现的数学运算.新MathOps分类的接口部分应该如下所示.
#import "Fraction.h" #interface Fraction (MathOps) -(Fraction *) add: (Fraction *) f; -(Fraction *) mul: (Fraction *) f; -(Fraction *) sub: (Fraction *) f; -(Fraction *) div: (Fraction *) f; @end;
注意:这既是接口部分的定义,也是现有接口部分的扩展.因此必须包括原始接口部分.这样编译器就知道Fraction类.
@implementation Fraction(MathOps) //code for category methods @end;
@protocol NSCopying - (id)copyWithZone: (NSZone *) zone; @end;
相关推荐
fort0 2020-05-16
81570790 2020-04-16
86540698 2020-04-08
zhoutaifeng 2020-03-07
好好学习天天 2020-03-06
InterestSoul 2020-02-17
82467413 2019-12-31
84407518 2012-07-16
81570790 2013-07-01
83254851 2013-08-29
84334052 2019-11-19
86540698 2019-11-19
84467715 2011-07-25
81731290 2014-03-22
85437811 2014-03-22
dahuichen 2019-10-25
ObjectiveC 2011-09-20
80530297 2015-04-14
80530297 2015-04-20