早教吧 育儿知识 作业答案 考试题库 百科 知识分享

objectivec定义一个矩形类,包括长,宽2个实例变量,定义计算周长和面积的方法,定义一个方法完成对长和宽的赋值.定义一个正方形类继承矩形类,定义方法对正方形的边长赋值.在main方法中创建

题目详情
objective c
定义一个矩形类,包括长,宽2个实例变量,定义计算周长和面积的方法,定义一个方法完成对长和宽的赋值.定义一个正方形类继承矩形类,定义方法对正方形的边长赋值.在main方法中创建矩形和正方形的对象,并计算其面积和周长.
▼优质解答
答案和解析
矩形Rectangle头文件:
@interface Rectangle:NSObject
{
float _long;//长
float _width; //宽
}
@property(nonatomic,assign) float _long;
@property(nonatomic,assign) float _width;
-(float)calPerimeter;//计算周长
-(float)calArea;//计算面积
-(void)setWidth:(float)width withLong:(float)long;//对长和宽赋值
Rectangle实现文件:
@implementation Rectangle
@synthesize _long;
@synthesize _width;
-(float)calPerimeter
{
return 2*(_long+_width);
}
-(float)calArea
{
return _long*_width;
}
-(void)setWidth:(float)width withLong:(float)long
{
_long = long;
_width = width;
}
继承自矩形的正方形类Square的.h头文件:
@interface Square:Rectangle
- (void)setEdge:(float)edge;//对正方形的边长赋值
正方形类Square的.m实现文件
@implementation Square
- (void)setEdge:(float)edge
{
_width = edge;
_long = edge;
}
main函数调用:
Rectangle *rectangle= [[Rectanglealloc] init];
[rectangle setWidth:3 withLong:4];
NSLog(@"矩形周长和面积分别为:%f,%f",[rectangle calPerimeter],[rectangle calArea]);
Square *square= [[Square alloc] init];
[square setEdge:5];
NSLog(@"正方形周长和面积分别为:%f,%f",[squarecalPerimeter],[squarecalArea]);
希望可以帮到你,有不懂的地方可以继续问我,有错误的地方也请指出,纯手敲的,望采纳!