iOS之03-类的合理设计

时间:2023-03-09 13:32:29
iOS之03-类的合理设计

以下代码为了充分学习理解 类与对象

类与对象的定义 

  类就是将事物的共有属性和方法抽离出来形成的;类是现实世界或思维世界中的实体在计算机中的反映,它将数据以及这些数据上的操作封装在一起。

  对象是具有类类型的变量。类和对象是面向对象编程技术中的最基本的概念。

类对象的关系

  类是对象的抽象,而对象是类的具体实例。类是抽象的,不占用内存,而对象是具体的,占用存储空间。类是用于创建对象的蓝图,它是一个定义包括在特定类型的对象中的方法和变量的软件模板。
 /*
学生
成员变量:性别、生日、体重、最喜欢的颜色、养的狗(体重、毛色、吃、跑)
方法:吃、跑步、遛狗、喂狗 */ #import <Foundation/Foundation.h> // 性别枚举
typedef enum {// 枚举类型常量一般是以枚举名开头(规范)
SexMan, //
SexWoman //
} Sex; // 生日结构体
typedef struct {
int year;
int month;
int day;
} Date; // 颜色结构体
typedef enum {
ColorBlack,//
ColorRed, //
ColorGreen //
} Color; // Dog类的声明
@interface Dog : NSObject
{// 成员变量
@public
double weight; //体重
Color curColor;//毛色
}
// 方法声明
- (void)eat;
- (void)run;
@end // Dog类的实现
@implementation Dog
// 狗吃东西的方法
- (void)eat {
weight++;
NSLog(@"吃完这次后的体重是%.2f", weight);
}
// 狗跑的方法
- (void)run {
weight--;
NSLog(@"跑完这次后的体重是%.2f", weight);
}
@end // Student类的声明
@interface Student : NSObject
{
@public
char *name; // 名字
Sex sex; // 性别
Date birthday; // 生日
double weight; // 体重(kg)
Color favColor; // 最喜欢的颜色
Dog *dog; // 养的狗
}
// 人吃东西的方法声明
- (void)eat;
// 人跑步的方法声明
- (void)run;
// 输出人的信息方法声明
- (void)print;
// 人遛狗方法声明
- (void)liuDog;
// 人喂狗方法声明
- (void)feed;
@end // Student类的实现
@implementation Student // 人吃东西的方法实现
- (void)eat {
weight++;
NSLog(@"狗吃完这次后的体重是%.2f", weight);
} // 人跑步的方法实现
- (void)run {
weight--;
NSLog(@"狗跑完这次后的体重是%.2f", weight);
} // 输出人的信息方法实现
- (void)print {
NSLog(@"名字 = %s,性别 = %d,生日 = %d-%d-%d,体重 = %.2f,喜欢的颜色 = %d", name, sex, birthday.year, birthday.month, birthday.day, weight, favColor);
} // 人遛狗方法实现
- (void)liuDog {
// 让狗跑起来(调用狗的run方法)
[dog run];
} // 人喂狗方法实现
- (void)feed {
// 让狗吃东西(调用狗的eat方法)
[dog eat];
}
@end int main() { // 创建一个学生对象
Student *s = [Student new]; // 人的属性赋值
s->name = "Jack";
s->weight = ;
s->sex = SexMan;
// 生日;
/*
s->birthday.year = 2011;
s->birthday.month = 9;
s->birthday.day = 10;
*/
Date d = {, , };
s->birthday = d;
// 喜欢的颜色
s->favColor = ColorRed; // 人的方法调用
[s eat];
[s eat];
[s run];
[s run];
[s print]; // 创建一个狗的对象
Dog *dog = [Dog new]; // 狗的属性赋值
dog->weight = ;
dog->curColor = ColorBlack; // 将狗对象赋值给人的 狗属性
s->dog = dog; // 人的方法调用
[s liuDog];
[s feed]; return ;
}