类的合理设计

2019-03-07  本文已影响0人  AmberAlbee

main.m

#import <Foundation/Foundation.h>

#import "Student.h"

#import "Dog.h"

int main(int argc, const char * argv[])

{

Student *s = [Student new];

Dog *dog = [Dog new];

s->weight = 60;

s->sex = SexWoman;

s->favColor = ColorGreen;

s->birthday.year = 1995;

s->birthday.month = 2;

s->birthday.day = 1;

[s run];

[s eat];

[s print];

dog->weight = 20;

dog->curColor = ColorGreen;

[s eatDog];

[s playDog];

[dog run];

[dog eat];

return 0;

}


Student.h

/*

类名:Student

属性:性别,生日,体重,喜欢的颜色,狗(体重,毛的颜色,吃,跑)

方法:吃,跑步,喂狗,遛狗

*/

#impprt <Foundation/Foundation.h>

@class Dog;

typedef enum //枚举

{

SexMan, //枚举常量命名一般以枚举类型的名称开头

SexWoman //枚举每项以逗号隔开,最后一项不写

}Sex;

typedef struct //结构体

{

int year;

int month;

int day;

}Date;

typedef enum

{

ColorBlack,

ColorRed,

ColorGreen

}Color;

@interface Student : NSObject

{

@public

Sex sex;

Date birthday;

double weight; //包括小数点后

Color favColor;

Dog *dog;

}

- (void) run;

- (void) eat;

- (void) print;

- (void) eatDog;

- (void) playDog;

@end


Student.m

#import "Student.h"

@implementation Student

- (void) run

{

weight -=1;

NSLog(@"学生成功减掉一斤肉");

}

- (void) eat

{

weight +=1;

NSLog(@"学生长了一斤肉");

}

- (void) print

{

NSLog(@"性别=%d,体重=%f,最喜欢的颜色=%d,生日是=%d-%d-%d",sex,weight,favColor,birthday);

}

- (void) eatDog

{

// dog->weight +=1; 面向过程,非面向对象

[dog eat];

}

- (void) playDog

{

[dog run];

}

@end


Dog.h

#import <Foundation/Foundation.h>

//狗(体重,毛的颜色,吃,跑)

typedef enum

{

ColorBlack,

ColorRed,

ColorGreen

}Color;

@interface Dog : NSObject

{

@public

double weight;

Color curColor;

}

- (void) run;

- (void) eat;

@end


Dog.m

#import "Dog.h"

@implementation Dog

- (void) run

{

weight -=1;

NSLog(@"狗成功减掉一斤肉");

}

- (void) eat

{

weight +=1;

NSLog(@"狗长了一斤肉");

}

@end


@class A:只调用类

#import "A.h":调用类和方法


上一篇下一篇

猜你喜欢

热点阅读