Kochan-Objective-Cでのプログラミング。
2行のコードを理解できません。(「コメント」としてマークされています)
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は呼び出されませんでした。