Kochan- 在 Objective-C 中编程。
两行代码看不懂。(标记为“评论”)
XYPoint.h 接口文件
#import <Foundation/Foundation.h>
@interface XYPoint: NSObject
{
int x;
int y;
}
@property int x, y;
-(void) setX: (int) xVal andY: (int) yVal;
@end
XYPoint.m 实现文件
#import "XYPoint.h"
@implementation XYPoint.h
@synthesize x, y;
-(void) setX: (int) xVal andY: (int) yVal
{
x = xVal;
y = yVal;
}
@end
Rectangle.h 接口文件
#import <Foundation/Foundation.h>
@class XYPoint;
@interface Rectangle: NSObject
{
int width;
int height;
XYPoint *origin; // What does this line mean?
}
@property int width, height;
-(XYPoint *) origin;
-(void) setOrigin: (XYPoint *) pt;
-(void) setWidth: (int) w andHeight: (int) h;
-(int) area;
-(int) perimeter;
@end
Rectangle.m 实现文件
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(void) setWidth: (int) w andHeight: (int) h
{
width = w;
height = h;
}
–(void) setOrigin: (XYPoint *) pt
{
origin = pt;
}
–(int) area
{
return width * height;
}
–(int) perimeter
{
return (width + height) * 2;
}
–(XYPoint *) origin
{
return origin;
}
@end
测试程序
#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; // What does this line mean?
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;
}
输出
Rectangle w = 5, h = 8
Origin at (100, 200)
Area = 40, Perimeter = 26
Kochan 对这一行的解释 myRect.origin = myPoint; 是:“将矩形的宽度和高度分别设置为 5 和 8 后,您调用了 setOrigin 方法将矩形的原点设置为 myPoint 指示的点。” 但是我们没有调用 setOrigin!