------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
类的设计
/*
1 类的设计
类名的第一个字母必须是大写
不能有下划线
多个英文单词,用驼峰表示
1>类的声明
声明对象的属性和方法
属性(成员变量/实例变量)
方法的声明
2>类的实现
实现@interface中声明的方法
方法:
1. 对象方法都是以减号 - 开头
2. 对象方法的声明必须写在@interface 和 @end之间
对象方法的实现必须写在@implementation 和 @end之间
3. 对象方法只能由对象来调用
4. 对象方法归类/对象所有
函数:
1. 函数能写在文件中得任意位置(@interface 和 @end除外)
函数归文件所有
2. 函数调用不依赖于对象
3. 函数内部不能直接通过成员变量名访问某个对象的成员变量
*/
/*
#import
//类的设计
@interface Car : NSObject
{ //成员变量(实例变量/属性)
@public
int age;
int speed;
}
-(void)run;
@end
//类的实现:实现@interface中声明的方法
@implementation Car
-(void)run
{ //不支持打印以%s格式打印的ch类型的纯中文字符串
//NSString %@格式输出,是oc中特有的字符串格式
NSLog(@"这车的时速是 %d km/h!",speed);
}
@end
int main(int argc, const char * argv[]) {
//定义了一个指针变量指向了Car类型的 对象
Car *p = [Car new];
p->speed = 100;
[p run];
NSString *p2 = @"小白";
NSLog(@"p2 = %@",p2);
return 0;
}
*/
//类的合理设计
#import
//定义新类型
typedef enum{
SexMan,
SexWomen
}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
{ //每吃一次,体重就加1
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 *p = [Student new];
Dog *d = [Dog new];
d->curColor=ColorGreen;
d->weight=20;
p->dog=d;
//行为的执行
[p liuDog];
[p weiDog];
return 0;
}