我制作程序,它将找到两个矩形交叉的区域。我有这个矩形的高度,宽度和坐标。
但它不会工作! Xcode在此行(Rectangle.m)上使用“Thread 1:SIGNAL SIGABRT”终止程序:
reswidth = (origin.x + width) - (second.origin.x + second.width);
所以,这是我的代码:
main.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;
}
Rectangle.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
Rectangle.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
感谢!!!!
答案 0 :(得分:1)
您没有在矩形类中实现方法-(XYPoint*) origin
,因此在执行second.origin
时会崩溃。只需将origin设置为矩形类中的属性即可。也不要过多使用新方法,这是不好的做法,并阻止你看到可能实现的其他init方法