Objective-C 程序设计,第六版第十章习题答案

1.

 1 - (id) init
 2 {
 3     return [self initWithWidth: 0 andHeight: 0];
 4 }
 5 
 6 - (id) initWithWidth: (int) w andHeight: (int) h
 7 {
 8     self = [super init];
 9     if (self) {
10         [self setWidth: w andHeight: h];
11     }
12     return self;
13 }

2.

 1 - (id)init
 2 {
 3     return [self initWithSide:0];
 4 }
 5 
 6 - (id) initWithSide: (int) side
 7 {
 8     self = [super init];
 9     if (self) {
10         [self setSide:side];
11     }
12     return self;
13 }

3.

 1 //.m文件定义静态变量  增加类方法
 2 #import "Fraction.h"
 3 
 4 static int gCounter;
 5 
 6 @implementation Fraction
 7 @synthesize numerator, denominator;
 8 
 9 
10 - (Fraction *) add: (Fraction *) f
11 {
12     Fraction *result = [[Fraction alloc] init];
13     
14    result.numerator = numerator * f.denominator + denominator * f.numerator;
15    result.denominator = denominator * f.denominator;
16     
17     [result reduce];
18     gCounter++;
19     return result;
20 }
21 
22 + (int) count
23 {
24     return gCounter;
25 }

4.

typedef enum {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} Day;

5. 枚举类型不知道怎么用

 1         typedef Fraction * FractionObj;
 2         
 3         FractionObj f1 = [[Fraction alloc] init],
 4                     f2 = [[Fraction alloc] init];
 5         
 6         [f1 setTo: 1 over: 2];
 7         [f2 setTo: 2 over: 3];
 8         
 9         [f1 print];
10         [f2 print];

6.略.