-2
@interface Rectangle: NSObject
-(void) setOrigin : (XYPoint *) pt;
-(XYPoint *) origin;
...
@end

#import "XYPoint.h"
#import "Rectangle.h"
@implementation Rectangle
-(void) setOrigin : (XYPoint *) pt
{
   origin = pt;
}

-(XYPoint *) origin 
{
   return origin;
}
@end

@interface XYPoint: NSObject
@property int x, y;
-(void) setX: (int) xVall andY; (int) yVal;
@end

#import "XYPoint.h"
@implementation XYPoint
@synthesize x, y
-(void) setX: (int) xVal andY: (int) yVal
{
   x = xVal;
   y = yVal;
}
@end

上記はクラスの一部です。これがメインです

int main (int argc, const char* argv[])
{
    XYPoint* myPoint = [[XYPoint alloc]init];
    Rectangle* myRect = [[Rectangle alloc]init];

    [myPoint setX: 200 andY: 100];

    [myRect setOrigin: myPoint];
    NSLog(@"origin of rectangle: (%i, %i)", myRect.origin.x, myRect.origin.y);
    return 0;
}

これは私が期待したようにうまくいきます。でも、方法を変えると

setOrigin: (XYPoint *) pt

Rectangle クラスで、

-(void) setOrigin: (XYPoint *) pt
{
    origin.x = pt.x;
    origin.y = pt.y;
} 

x と y の両方に 0 の値を出力するだけです。これら2つの方法の違いは何ですか。私にとっては、同じように思えます。

4

1 に答える 1

2

クラスの初期化でオブジェクトを使用しないallocinit思います...originRectangle

于 2013-03-17T20:52:01.197 に答える