. 定义一个学生类,需要有姓名,年龄,考试成绩三个成员属性,创建5个对象,属性可以任意值。(Objective-C)
1> 不使用@property,手动编写他们的访问器方法(getter和setter),注意内存管理(手动管理 内存)
2> 增加一个便利构造器(快速构造器)
3> 使用NSLog输出学生对象时,输出信息格式为:My Name Is XXX Age Is XXX Score Is XXX
4> 对5个学生对象按照成绩—》年龄—》姓名优先级排序(成绩相同按照年龄排序,成绩年龄相同按照姓名排序
@interface HMStudent : NSObject
{
NSString *_name;
int _age;
float _score;
}
-(void)setName:(NSString *)name;
-(NSString *)name;
-(void)setAge:(int)age;
-(int)age;
-(void)setScore:(float)score;
-(float)score;
-(instancetype)initWithName:(NSString *)name andAge:(int)age andScore:(float)score;
+(instancetype)peopleWithName:(NSString *)name andAge:(int)age andScore:(float)score;
-(NSString *)description;
+(NSString *)description;
@end
@implementation HMStudent
-(void)setName:(NSString *)name
{
_name = name;
}
-(NSString *)name
{
return _name;
}
-(void)setAge:(int)age
{
_age = age;
}
-(int)age
{
return _age;
}
-(void)setScore:(float)score
{
_score = score;
}
-(float)score
{
return _score;
}
-(void)dealloc
{
NSLog(@"我勒个去");
[_name release];
[super dealloc];
}
-(instancetype)initWithName:(NSString *)name andAge:(int)age andScore:(float)score
{
if (self = [super init])
{
self.name = name;
self.age = age;
self.score = score;
}
return self;
}
+(instancetype)peopleWithName:(NSString *)name andAge:(int)age andScore:(float)score
{
return [[self alloc]initWithName:(NSString *)name andAge:(int)age andScore:(float)score];
}
-(NSString *)description
{
return [NSString stringWithFormat:@"My Name Is %@ Age Is %d Score Is %.2f",_name,_age,_score];
}
+(NSString *)description
{
return [self description];
}
@end
int main(int argc, const char * argv[])
{
HMStudent *student[5];
student[0] = [HMStudent peopleWithName:@"jack" andAge:18 andScore:89];
student[1] = [HMStudent peopleWithName:@"rose" andAge:19 andScore:89];
student[2] = [HMStudent peopleWithName:@"tom" andAge:18 andScore:89];
student[3] = [HMStudent peopleWithName:@"jerry" andAge:19 andScore:95];
student[4] = [HMStudent peopleWithName:@"lucy" andAge:17 andScore:80];
//NSLog(@"%@",student[0]);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5 - i -1;j++)
{
if (student[j].score >= student[j+1].score)
{
if (student[j].score == student[j+1].score && student[j].age >= student[j+1].age)
{
if (student[j].score == student[j+1].score && student[j].age == student[j+1].age && [student[j].name compare:student[j+1].name]== 1)
{
HMStudent *temp = student[j];
student[j] = student[j+1];
student[j+1] = temp;
}
HMStudent *temp = student[j];
student[j] = student[j+1];
student[j+1] = temp;
}
HMStudent *temp = student[j];
student[j] = student[j+1];
student[j+1] = temp;
}
}
}
for (int i = 0; i < 5; i++)
{
NSLog(@"%@",student[i]);
}
return 0;
} |
|