OC类的设计

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------



  类的设计


/*

 1 类的设计

 类名的第一个字母必须是大写

 不能有下划线

 多个英文单词,用驼峰表示

 1>类的声明

 声明对象的属性和方法

 属性(成员变量/实例变量)

 方法的声明

 

 2>类的实现

 实现@interface中声明的方法

 


 

 方法:

 1. 对象方法都是以减号开头

 2. 对象方法的声明必须写在@interface @end之间

    对象方法的实现必须写在@implementation @end之间

 3. 对象方法只能由对象来调用

 4. 对象方法归类/对象所有

 

 函数:

 1. 函数能写在文件中得任意位置(@interface @end除外)

 函数归文件所有

 2. 函数调用不依赖于对象

 3. 函数内部不能直接通过成员变量名访问某个对象的成员变量

 */

/*

#import <Foundation/Foundation.h>


//类的设计

@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 <Foundation/Foundation.h>


//定义新类型


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;

    

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值