//
// main.m
// 05作业
//
// Created by apple on 15/8/9.
// Copyright (c) 2015年 金诗妍. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <math.h>
// Point2D类
@interface Point2D : NSObject
{
double _x; //x值
double _y; //y值
}
// x的setter和getter
- (void)setX:(double)x;
- (double)x;
// y的setter和getter
- (void)setY:(double)y;
- (double)y;
// 一个类对象方法同时设置x和y
- (void)setX:(double)x andY:(double)y;
// 计算跟其他点的距离
- (double)distanceWithOther:(Point2D *)other;
// 计算两点间距离
+ (double)distanceBetweenPoint1:(Point2D *)p1 andPoint2:(Point2D *)p2;
@end
/**********方法**********/
@implementation Point2D
// x的setter和getter
- (void)setX:(double)x
{
_x = x;
}
- (double)x
{
return _x;
}
//y的setter和getter
- (void)setY:(double)y
{
_y = y;
}
- (double)y
{
return _y;
}
// 同时设置x和y
- (void)setX:(double)x andY:(double)y
{
/*
第一种写法:
_x=x;
_y=y;
第二种写法:
self->_x=x;
self->_y=y;
*/
//推荐写法,因为有时需要对x,y进行过滤
[self setX:x];
[self setY:y];
}
// 计算与另外一个点的距离
- (double)distanceWithOther:(Point2D *)other
{
//******正常算法
double xDelta = _x - [other x];// 一般用get方法来访问成员变量,内部变量直接写也行(_x)
double xDeltaPF = pow(xDelta,2);
double yDelta = _y - [other y];
double yDeltaPF = pow(yDelta,2);
return sqrt(xDeltaPF+yDeltaPF);
//********
//或者调用类方法
//return [Point2D distanceBetweenPoint1:self andPoint2:other]; //对象方法调用类方法
}
// 计算两点间距离
+ (double)distanceBetweenPoint1:(Point2D *)p1 andPoint2:(Point2D *)p2
{
/****正常算法
double xDelta = [p1 x] - [p2 x];
double xDeltaPF = pow(xDelta,2);
double yDelta = [p1 y] - [p2 y];
double yDeltaPF = pow(yDelta,2);
return sqrt(xDeltaPF+yDeltaPF);
*****/
return [p1 distanceWithOther:p2]; // 类方法调用对象方法
}
@end
int main()
{
Point2D *p1 = [Point2D new];
//(10,15)
[p1 setX:10 andY:15];
Point2D *p2 = [Point2D new];
//(13,19)
[p2 setX:13 andY:19];
//对象方法调用
//double dis = [p1 distanceWithOther:p2];
// 类方法调用
double dis = [Point2D distanceBetweenPoint1:p1 andPoint2:p2];
NSLog(@"%.2f",dis);
return 0;
}