/*
类设计练习
1.设计一个人类,每个人都有姓名,生日,性别.每个人都有说话与笑的方法.
2.设计一个家庭类有在三个成员,父亲 母亲 孩子.
注意:类的属性可以是任意类型
2.在类的设计的时候,注意尽量高内聚,低耦合.
有关联的属性尽量封装成一个模块,以实现高内聚.而模块与模块之间要尽量独立,以实现低耦合.---类的设计原则
*/
#import <Foundation/Foundation.h>
typedef struct{
int year;
int month;
int day;
} Date;
typedef enum{
MAN,
WOMAN,
}SEX;
//定义一个人类
@interface Person : NSObject{
@public
char *name;//姓名
Date birthDay;//生日
SEX sex;//性别
}
-(void) talk:(char *) s;//说话的方法
-(void) smile;//笑
-(void) printMe;//打印自已的属性
@end
@implementation Person
-(void) talk:(char *) s{
NSLog(@"%s讲了一句话:%s",name,s);
}
-(void) smile{
NSLog(@"%s笑了...",name);
}
-(void) printMe{
NSLog(@"姓名:%s,生日:%d年-%d月-%d日,性别:%d",name,birthDay.year,birthDay.month,birthDay.day,sex);
}
@end
//定义一个家庭类
@interface Family : NSObject{
@public
Person* dad;
Person* mom;
Person* child;
}
-(void) printAll;
@end
@implementation Family
-(void) printAll{
[dad printMe];
[mom printMe];
[child printMe];
}
@end
int main(){
//创建对象
Person * p=[Person new];
//给属性赋值
p->name="fred";
//给生日结构体赋值
p->birthDay.year=1980;
p->birthDay.month=1;
p->birthDay.day=1;
//性别赋值
p->sex=MAN;
/* NSLog(@"姓名:%s,生日:%d年-%d月-%d日,性别:%d",p->name,p->birthDay.year,p->birthDay.month,p->birthDay.day,p->sex);
[p printMe];
[p printMe];
[p printMe];
//方法测试
[p talk:"haha"];
[p smile];
[p printMe];
*/
//给家庭类的三个成员赋值
//1.创建家庭类的对象
Family* f=[Family new];
//给每个在员赋值
f->dad=p;
//创建一个对象:母亲
Person * mom=[Person new];
//给属性赋值
mom->name="mary";
//给生日结构体赋值
mom->birthDay.year=1982;
mom->birthDay.month=2;
mom->birthDay.day=14;
//性别赋值
mom->sex=WOMAN;
f->mom=mom;
//创建一个对象:小孩
Person * child=[Person new];
//给属性赋值
child->name="AA";
//给生日结构体赋值
child->birthDay.year=2004;
child->birthDay.month=5;
child->birthDay.day=18;
//性别赋值
child->sex=MAN;
f->child=child;
// Person *pdad=f->dad;
// [pdad printMe];
// [f->dad printMe];
// [f->mom printMe];
// [f->child printMe];
[f printAll];
return 0;
}
|
|