通过上一篇的学习,我们已经可以设置矩形或者正方形(Rectangle)的宽、高及原点。首先,完整地看一下接口文件Rectangle.h,然后再来接着引入我们这篇文章要讲的主题@class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#import <Foundation/Foundation.h>
@
class
XYPoint;
@interface Rectangle: NSObject
{
int
width;
int
height;
XYPoint *origin;
}
@property
int
width, height;
-(XYPoint *) origin;
-(
void
) setOrigin: (XYPoint *) pt;
-(
void
) setWidth: (
int
) w andHeight: (
int
) h
-(
int
) area;
-(
int
) perimeter;
@end
|
@class XYPoint;
这是因为编译器在遇到为Rectangle定义的实例变量XYPoint时,必须了解XYPoint是什么。类名还分别用在setOrigin:和origin方法的参数及返回类型声明中。你还有另一个选择,可以如下所示导入头文件来代替它:
#import “XYPoint.h”
使用@class指令提高了效率,因为编译器不需要处理整个XYPoint.h文件(虽然它很小)。而只需知道XYPoint是一个类名字。如果需要引用XYPoint类中方法,@class指令是不够的,因为编译器需要更多消息。它需要知道该方法中有多少参数、它们是什么类型、方法的返回类型是什么。
下面填充新的XYPoint类和Rectangle方法的空白,这样就可以在一个程序中测试所有内容。首先,下面的代码显示了XYPoint类的实现文件。
1
2
3
4
5
6
7
8
9
10
|
#import “XYPoint.h”
-(
void
) setOrigin: (XYPoint *) pt
{
origin = pt;
}
-(XYPoint *) origin
{
return
origin;
}
@end
|
XPoint.h接口文件:
1
2
3
4
5
6
7
8
9
|
#import <Foundation/Foundation.h>
@interface XYPoint: NSObject
{
int
x;
int
y;
}
@property
int
x, y;
-(
void
) setX: (
int
) xVal andY: (
int
) yVal;
@end
|
1
2
3
4
5
6
7
8
9
|
#import “XYPoint.h”
@implementation XYPoint
@synthesize x, y;
-(
void
) setX: (
int
) xVal andY: (
int
) yVal
{
x = xVal;
y = yVal;
}
@end
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#import <Foundation/Foundation.h>
@
class
XYPoint;
@interface Rectangle: NSObject
{
int
width;
int
height;
XYPoint *origin;
}
@property
int
width, height;
-(XYPoint *) origin;
-(
void
) setOrigin: (XYPoint *) pt;
-(
void
) setWidth: (
int
) w andHeight: (
int
) h;
-(
int
) area;
-(
int
) perimeter;
@end
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#import “Rectangle.h”
@implementation Rectangle
@synthesize width, height;
-(
void
) setWidth: (
int
) w andHeight: (
int
) h
{
width = w;
height = h;
}
–(
void
) setOrigin: (Point *) pt
{
origin = pt;
}
–(
int
) area
{
return
width * height;
}
–(
int
) perimeter
{
return
(width + height) * 2;
}
–(Point *) origin
{
return
origin;
}
@end
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#import “Rectangle.h”
#import “XYPoint.h”
int
main (
int
argc,
char
*argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Rectangle *myRect = [[Rectangle alloc] init];
XYPoint *myPoint = [[XYPoint alloc] init];
[myPoint setX: 100 andY: 200];
[myRect setWidth: 5 andHeight: 8];
myRect.origin = myPoint;
NSLog (@”Rectangle w = %i, h = %i”,
myRect.width, myRect.height);
NSLog (@”Origin at (%i, %i)”,
myRect.origin.x, myRect.origin.y);
NSLog (@”Area = %i, Perimeter = %i”,
[myRect area], [myRect perimeter]);
[myRect release];
[myPoint release];
[pool drain];
return
0;
}
|
1
2
3
|
Rectangle w = 5, h = 8
Origin at (100, 200)
Area = 40, Perimeter = 26
|