继承的简单例子(From Kochan's Book)

时间:2012-10-09 01:18:33

标签: objective-c

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; 是:&#34;将矩形的宽度和高度分别设置为5和8之后 调用setOrigin方法将矩形的原点设置为指示的点 myPoint&#34。 但是我们没有调用setOrigin!

1 个答案:

答案 0 :(得分:1)

myRect.origin = myPoint;

相同(差不多)
[myRect setOrigin:myPoint];

这只是实现相同结果的另一种方式。

正如马赫什解释的那样,

XPoint *origin;

声明一个名为origin的指针(变量),类型为XPoint。