类的合理设计 补充:结构体和Dog类的set get方法
发布网友
发布时间:2022-12-30 03:19
我来回答
共1个回答
热心网友
时间:2023-10-28 21:20
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];
date b = {2001,02,01};
[s setBirthday:b];
[s birthday];
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;
- (void)setBirthday:(Date)birthday;
- (Date)birthday;
- (void)setDog:(Dog *)dog;
- (Dog *)dog;
@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];
// }
- (void)setBirthday:(Date)birthday
{
NSLog(@"调用了它的set方法");
_birthday = birthday;
}
- (date)birthday
{
NSLog(@"调用了它的get方法");
return _birthday;
}
;@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":调用类和方法