#import <Foundation/Foundation.h>
#import <math.h>
@interface Point2D : NSObject
{
double _x; // x值
double _y; // y值
}
// x值的getter和setter
- (void)setX:(double)x;
- (double)x;
// y值的getter和setter
- (void)setY:(double)y;
- (double)y;
// 同时设置x和y
- (void)setX:(double)x andY:(double)y;
//计算根其他点距离
- (double)distanceWithOther:(Point2D *)other;
//类方法计算两个点之间的距离
+ (double)distanceWithOther1:(Point2D *)p1 andPoint2:(Point2D *)p2;
@end
@implementation Point2D
// x值的getter和setter
- (void)setX:(double)x
{
self->_x = x;
}
- (double)x
{
return _x;
}
// y值的getter和setter
- (void)setY:(double)y
{
self->_y = y;
}
- (double)y
{
return _y;
}
// 同时设置x和y
- (void)setX:(double)x andY:(double)y
{
[self setX:x];
[self setY:y];
}
//计算两个点之间的距离
- (double)distanceWithOther:(Point2D *)other
{
//return [Point2D distanceWithOther1:self andPoint2:other];
double xDelta = [self x] - [other x];
double xDeltaPF = pow(xDelta, 2);
double yDelta = [self y] - [other y];
double yDeltaPF = pow(yDelta, 2);
return sqrt(xDeltaPF + yDeltaPF);
}
//类方法计算两个点之间的距离
+ (double)distanceWithOther1:(Point2D *)p1 andPoint2:(Point2D *)p2
{
// 调用在类方法中的对方法
return [p1 distanceWithOther:p2];
}
@end
@interface Circle : NSObject
{
//半径
double _radius;
//圆心
Point2D *_point;
}
// 半径的getter和setter
- (void)setRadius:(double)radius;
- (double)radius;
//圆心的getter和setter
- (void)setPoint:(Point2D *)point;
- (Point2D *)point;
//判断两个圆是否重叠
//类方法
+ (BOOL)isInteractBetweenCircle1:(Circle *)c1 andCircle2:(Circle *)c2;
//对象方法
- (BOOL)isInteractBetweenCircle:(Circle *)other;
@end
@implementation Circle
// 半径的getter和setter
- (void)setRadius:(double)radius
{
_radius = radius;
}
- (double)radius
{
return _radius;
}
//圆心的getter和setter
- (void)setPoint:(Point2D *)point
{
_point = point;
}
- (Point2D *)point;
{
return _point;
}
//对象方法
- (BOOL)isInteractBetweenCircle:(Circle *)other
{
//看圆心距离和半径长度关系
//圆心长度
Point2D *p1 = [self point];
Point2D *p2 = [other point];
double distance = [p1 distanceWithOther:p2]; //5
//半径和
NSLog(@"圆心长 %f",distance);
double radiusSum = [self radius] + [other radius]; //7
NSLog(@"半径长 %f",radiusSum);
return distance < radiusSum;
}
//判断是否重叠
+ (BOOL)isInteractBetweenCircle1:(Circle *)c1 andCircle2:(Circle *)c2
{
return [c1 isInteractBetweenCircle:c2];
}
@end
int main()
{
//凡是对象都有*
/*
Point2D *p1 = [Point2D new];
[p1 setX:10 andY:15];
Point2D *p2 = [Point2D new];
[p2 setX:10 andY:12];
//double d1 = [p1 distanceWithOther:p2];
double d1 = [Point2D distanceWithOther1:p1 andPoint2:p2];
NSLog(@"%f ", d1);
*/
//c1
Circle *c1 = [Circle new];
[c1 setRadius:5];
Point2D *p1 = [Point2D new];
[p1 setX:10 andY:15];
[c1 setPoint:p1];
[[c1 point] setX:15];
//c1 5 (15,15)
//c2
Circle *c2 = [Circle new];
[c2 setRadius:2];
Point2D *p2 = [Point2D new];
[p2 setX:12 andY:19];
//设置圆心
[c2 setPoint:p2];
//c2 2 (12,19)
BOOL b1 = [c1 isInteractBetweenCircle:c2];
NSLog(@"%d",b1);
if (b1) {
NSLog(@"重叠");
}else
NSLog(@"不重叠");
return 0;
}