objective-c 类方法

#import <Foundation/Foundation.h>
/*
1.基本概念
直接可以用类名来执行的方法(类本身会在内存中占据存储空间,里面有类\对象方法列表)
2.类方法和对象方法对比
1)对象方法
以减号-开头
只能让对象调用,没有对象,这个方法根本不可能被执行
对象方法能访问实例变量(成员变量)

2)类方法
以加号+开头
只能用类名调用,对象不能调用
类方法中不能访问实例变量(成员变量)
使用场合:当不需要访问成员变量的时候,尽量用类方法
3)类方法和对象方法可以同名
*/
@interface calculator : NSObject
//加法	
+ (int)addWithX:(int)x and:(int) y;
//减法
+ (int)subWithX:(int)x and:(int) y;	
//乘法
+ (int)mulWithX:(int)x and:(int) y;
//除法
+ (double)divWithX:(int)x and:(int) y;	
@end

@implementation Calculator
//加法	
+ (int)addWithX:(int)x and:(int) y
{
	return x+y;
}
//减法
+ (int)subWithX:(int)x and:(int) y
{
	return x-y;
}
//乘法
+ (int)mulWithX:(int)x and:(int) y
{
	return x*y;
}
//除法
+ (double)divWithX:(int)x and:(int) y
{
	return (double)x/y;
}
@end

int main (int argc, const char *argv[]) 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];                         
	int x=8,y=5;
	
	NSLog(@"%d+%d=%d",x,y,[Calculator addWithX:x and:y]);  
    NSLog(@"%d-%d=%d",x,y,[Calculator subWithX:x and:y]);  
    NSLog(@"%d*%d=%d",x,y,[Calculator mulWithX:x and:y]);  
    NSLog(@"%d/%d=%f",x,y,[Calculator divWithX:x and:y]);  
   
    [pool drain];
    return 0;
}

运行结果


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值