类的设计
1.类的设计:
1> 类名
* 类名的第一个字母必须是大写
* 不能有下划线
* 多个英文单词,用驼峰标识
2> 属性
3> 行为(功能)
2.植物大战僵尸的僵尸
* 类名:Zoombie
* 属性:life、speed、gongjili
* 行为:walk、bite、die
3.雷电的飞机
* 类名:Plane
* 属性:life、gongjili、speed、bombCount
* 行为:fly、bomb、shoot、die
4.电脑
* 类名:Computer
* 属性:band、expireDate
* 行为:open、close
Car类的设计实例
#import <Foundation/Foundation.h>
@interface Car : NSObject
{
@public
int wheels;
int speed;
}
- (void)run;
@end
@implementation Car
- (void)run
{
NSLog(@"车子跑起来了");
}
@end
int main()
{
Car *p = [Car new];
Car *p2 = [Car new];
p2->wheels = 5;
p2->speed = 300;
[p2 run];
p->wheels = 4;
p->speed = 250;
[p run];
NSLog(@"车子有%d个轮子,时速位:%dkm/h", p->wheels, p2->speed);
return 0;
}
Person类的设计实例
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
@public
int age;
double weight;
}
- (void)walk;
- (void)eat;
@end
@implementation Person
- (void)walk
{
NSLog(@"%d岁、%f公斤的人走了一段路", age, weight);
}
- (void)eat
{
NSLog(@"%d岁、%f公斤的人在吃东西", age, weight);
}
@end
int main()
{
Person *p = [Person new];
p->age = 20;
p->weight = 40;
[p eat];
[p walk];
Person *p2 = [Person new];
p2->age = 30;
p2->weight = 60;
[p2 eat];
[p2 walk];
Person *p2 = [Person new];
p2->age = 30;
p2->weight = 50;
p = p2;
p->age = 40;
[p2 walk];
Person *p = [Person new];
p->age = 20;
p->weight = 50.0;
[p walk];
Person *p2 = [Person new];
p2->age = 30;
p2->weight = 60.0;
[p2 walk];
return 0;
}
类的合理设计
#import <Foundation/Foundation.h>
typedef enum {
SexMan,
SexWoman
} Sex;
typedef struct {
int year;
int month;
int day;
} Date;
typedef enum {
ColorBlack,
ColorRed,
ColorGreen
} Color;
@interface Dog : NSObject
{
@public
double weight;
Color curColor;
}
- (void)eat;
- (void)run;
@end
@implementation Dog
- (void)eat
{
weight += 1;
NSLog(@"狗吃完这次后的体重是%f", weight);
}
- (void)run
{
weight -= 1;
NSLog(@"狗跑完这次后的体重是%f", weight);
}
@end
@interface Student : NSObject
{
@public
Sex sex;
Date birthday;
double weight;
Color favColor;
char *name;
Dog *dog;
}
- (void)eat;
- (void)run;
- (void)print;
- (void)liuDog;
- (void)weiDog;
@end
@implementation Student
- (void)liuDog
{
[dog run];
}
- (void)weiDog
{
[dog eat];
}
- (void)print
{
NSLog(@"性别=%d, 喜欢的颜色=%d, 姓名=%s, 生日=%d-%d-%d", sex, favColor, name, birthday.year, birthday.month, birthday.day);
}
- (void)eat
{
weight += 1;
NSLog(@"学生吃完这次后的体重是%f", weight);
}
- (void)run
{
weight -= 1;
NSLog(@"学生跑完这次后的体重是%f", weight);
}
@end
int main()
{
Student *s = [Student new];
Dog *d = [Dog new];
d->curColor = ColorGreen;
d->weight = 20;
s->dog = d;
[s liuDog];
[s weiDog];
return 0;
}
void test()
{
Student *s = [Student new];
s->weight = 50;
s->sex = SexMan;
Date d = {2011, 9, 10};
s->birthday = d;
s->name = "Jack";
s->favColor = ColorBlack;
[s print];
}