1

我做了一个程序,它会找到两个矩形相交的区域。我有这个矩形的高度、宽度和坐标。

但它不会工作!Xcode 在此行 (Rectangle.m) 上使用“Thread 1: SIGNAL SIGABRT”终止程序:

reswidth = (origin.x + width) - (second.origin.x + second.width);

所以,这是我的代码:

主.m:

#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "XYPoint.h"

int main(int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [NSAutoreleasePool new];
    Rectangle *myrect1 = [Rectangle new];
    Rectangle *myrect2 = [Rectangle new];
    XYPoint *temp = [XYPoint new];

    [temp setX: 200 andY: 420];
    [myrect1 setOrigin:temp];
   [temp setX: 400 andY: 300];
   [myrect2 setOrigin:temp];
   [temp dealloc];

   [myrect1 setWidth:250 andHeight:75];
   [myrect2 setWidth:100 andHeight:180];

   double print = [myrect1 intersect:myrect2];

   NSLog(@"%g", print);

   [pool drain];

   return 0;

}

矩形.h:

#import <Foundation/Foundation.h>
#import "XYPoint.h"

@interface Rectangle : NSObject
{
double width;
double height;
XYPoint *origin;
}

@property double width, height;

-(XYPoint *) origin;
-(void) setOrigin: (XYPoint *) pt;
-(void) setWidth: (double) w andHeight: (double) h;
-(double) area;
-(double) perimeter;
-(double) intersect: (Rectangle *) second;

@end

矩形.m:

#import "Rectangle.h"

@implementation Rectangle

@synthesize width, height;

-(void) setOrigin:(XYPoint *)pt
{
    origin = [[XYPoint alloc] init];
    [origin setX: pt.x andY: pt.y];
}

-(void) setWidth: (double) w andHeight: (double) h
{
    width = w;
    height = h;
}

-(double) area
{
    return width * height;
}

-(double) perimeter
{
    return (width + height) * 2;
}

-(double) intersect:(Rectangle *) second
{
    double result,reswidth,resheight;
    reswidth = (origin.x + width) - (second.origin.x + second.width);
    if (reswidth<0) reswidth *= -1;
    resheight = (origin.y + height) - (second.origin.y + second.height);
    if (resheight<0) resheight *= -1;
    result = reswidth * resheight;
    if (result<0) result *= -1;
    return result;
}
@end

XYPoint.h:

#import <Foundation/Foundation.h>

@interface XYPoint : NSObject
{
    double x;
    double y;
}

@property double x,y;

-(void) setX:(double) xVal andY: (double) yVal;

@end

XYPoint.m:

#import "XYPoint.h"

@implementation XYPoint

@synthesize x,y;

-(void) setX:(double) xVal andY: (double) yVal
{
    x=xVal;
    y=yVal;
}

@end

谢谢!!!!

4

1 回答 1

1

您没有-(XYPoint*) origin在 rectangle 类中实现该方法,所以当您执行时会崩溃second.origin。只需将 origin 设置为 rectangle 类中的属性,它应该可以工作。也不要过多地使用新方法,这是不好的做法,并且会阻止您看到其他可能实现的 init 方法

于 2013-08-13T08:49:58.490 回答