所以這是我正在學習的一本書中的練習。我得到的鍛鍊工作正常,我瞭解它的大部分,除了,我不知道我是否完全缺少這裏的東西,但... 在世界上如何知道編譯器:初學者Objective-C,對內存和指針的引用
X = 168.354和y = 987.259屬於(的Xypoint)PT *
和
X = 10.00和y = 10.00屬於(的Xypoint)T *
我明白如何myPoint和myTranslate是單獨的對象XYPoint類和什麼,並且它們指向存儲X和Y的內存引用,但它如何將上述值分配給pt和t。我在這裏錯過了很多東西嗎?
在此先感謝。
下面的代碼:
接口
#import "XYPoint.h"
#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
@property float width, height;
-(XYPoint*) origin;
-(void) translate: (XYPoint *)t;
-(void) setOrigin: (XYPoint *) pt;
-(float) area;
-(float) perimiter;
-(void) setHeight:(float) h andWidth: (float) w;
@end
Implementation
#import "Rectangle.h"
#import "XYPoint.h"
@implementation Rectangle
{
XYPoint *origin ;
}
@synthesize height, width;
-(void) setHeight: (float) h andWidth: (float) w;
{
width = w;
height = h;
}
-(void) setOrigin:(XYPoint *)pt
{
if (! origin)
origin = [[XYPoint alloc]init];
origin.x = pt.x;
origin.y = pt.y;
}
-(void) translate: (XYPoint*)t
{
origin.x = origin.x + t.x;
origin.y = origin.y + t.y;
}
-(float) area
{
return width * height;
}
-(float) perimiter
{
return (width + height) * 2;
}
-(XYPoint *) origin
{
return origin;
}
@end
主要
#import "XYPoint.h"
#import "rectangle.h"
#import "Square.h"
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
Rectangle *myRect = [[Rectangle alloc]init];
XYPoint *myPoint = [[XYPoint alloc]init];
XYPoint *myTranslate = [[XYPoint alloc] init];
[myPoint setX: 168.354 andY: 987.259];
[myTranslate setX: 10.00 andY: 10.00 ];
myRect.origin = myPoint;
NSLog (@"Origin at %f, %f", myRect.origin.x, myRect.origin.y);
[myRect translate: myTranslate];
NSLog (@"Origin at %f, %f", myRect.origin.x, myRect.origin.y);
}
return 0;
}
輸出:
原點168.354004,987.258972 轉換爲178.354004,997.258972
我忘了一個文件,我有這個代碼在裏面 - (無效)setX的:(浮點)XVAL安迪:(浮點)利用yval { X = XVAL; y = yVal; } – ElScorcho
是的,那些真的沒有任何關係。對不起,我錯過了代碼中的代碼'myRect.origin = myPoint;'這會自動爲你調用'setOrigin:'。當你分配原始變量時,它會調用它的setter方法。所以'myRect。origin = myPoint;'和'[myRect setOrigin:myPoint]'實際上是一樣的東西(在這種情況下myPoint是'pt')。下面的翻譯文件也顯示了 – Fonix
謝謝。我認爲我開始更好地理解。 – ElScorcho