我正在学习一个Objective-C教程。书中有这个例子:
@interface
{
int width;
int height;
XYPoint *origin;
}
@property int width, height;
我认为:"嘿,XYPoint对象没有getter/setter。不过代码确实可以运行。" 现在我可能会回答自己的问题 :)
我想这是因为 "origin" 已经是一个指针,而 "width" 和 "height" 在幕后发生的事情是,将会创建指向它们的指针。
我是对的还是在胡说八道 :) ??
我就是不明白。这是主函数:
#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;
}
这里是Rectangle对象:
#import "Rectangle.h"
#import "XYPoint.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
我不理解 main 函数中的这行代码:myRect.origin = myPoint;
我没有为它编写设置器(setter)。
顺便说一下,感谢您的快速回复。