类方法和对象方法间的各种相互调用的实例

<p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"><span style="color: rgb(85, 85, 85);"><span style="line-height: 35px; font-family: Simsun;">     ------</span><a target=_blank target="_blank" href="http://www.itheima.com/" style="color: rgb(12, 137, 207); text-decoration: none; line-height: 35px; font-family: Simsun;">Java培训、Android培训、iOS培训、.Net培训</a><span style="line-height: 35px; font-family: Simsun;">、期待与您交流! -------</span>
</span></p><div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;">#import <Foundation/Foundation.h></span>
#pragma mark Car类的声明
@interface Car : NSObject
//类的行为(类方法的声明)
+(void)_speed:(int)speed;
//对象方法的声明
-(void)_lunzi:(int)lunzi;

@end
#pragma mark Car类的实现
@implementation Car
//类方法的实现
+(void)_speed:(int)speed{
    
    NSLog(@"\n车正在以%dm/s在跑",speed);
}

-(void)_lunzi:(int)lunzi{
    
    NSLog(@"宝马有%d个轮子",lunzi);
    
}

@end
#pragma mark Caculator类的声明
@interface Caculator : NSObject
{
    //Caculator类的成员变量(类的属性)
    
    int _result;
    
}
//类的行为
// 对象方法声明
-(void)add;
-(void)cheng:(Caculator *)p1;
//类方法的声明
+(void)chu;
+(void)jian:(int)num1 and:(int)num2;

@end

#pragma mark Caculator类的实现
@implementation Caculator
// 对象方法的实现
-(void)add{
    NSLog(@"\n对象方法的实现");
    
    //7)对象方法调用自身类的类方法
    [Caculator chu];
    //7)对象方法调用其他类的类方法
    [Car _speed:9];
    
    
}


-(void)cheng:(Caculator *)p1{
    
    NSLog(@"\n对象方法的实现");
    //2)在对象方法中可以调用自己类的其它对象方法
    [p1  add];//Caculator类的对象p,作为p1的参数传递到方法cheng中,再用p1作为对象进行调用
    //3)在对象方法中可以调用其它类的对象方法
    Car *s=[Car new];//在当前的对象方法中创建一个Car对象s,
    [s _lunzi:5];//然后用创建s调用Car类的对象方法
    
    
}

//类方法的实现
+(void)chu{
    
    NSLog(@"\n类方法的实现");
    //4)在Caculator类的类方法中可以调用自己的其它类方法
    [Caculator jian:6 and:9];//用类名直接调用
    //4)在Caculator类的类方法中可以调用其它类(Car)的类方法
    [Car _speed:12];//用类名直接调用
}


+(void)jian:(int)num1 and:(int)num2;{
    
    //1)  在类方法中不能使用类的成员变量
    //_result=num1+num2
    
    NSLog(@"\n在类方法中不能使用类的成员变量:%d",num1-num2);
    //4)在Caculator类的类方法中可以调用自己的其它类方法
    [self chu];//self的直接调用(1.用于同类中类方法的调用;2.用于同类中对象方法之间的调用)
    //5)同类中类方法调用对象方法
    Caculator *p2=[Caculator new];//创建Caculator类的一个对象q
    [p2 add];//用创建的对象q 调用
    //5)同类中的类方法调用其它类的对象方法
    Car *s1=[Car new];
    [s1 _lunzi:5];
    //6)方法不能调用自身会造成死循环(对象方法或类方法)
    //[Caculator jian:6 and:2];
    
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //Caculator类的对象的创建
        Caculator *p=[Caculator new];
        //对象方法的调用
        [p add];
        [p cheng:p];
        //类方法的调用
        [Caculator jian:4 and:9];
        
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值