类方法的实现 10月17号
设计一个“计算器(calculator)”类,实现两个数的 + - * /四则运算
思路:
首先创建一个类
类名:calculator
属性:第一个数num1,第二个数num2, 运算结果result
行为:加:add, 减:jian, 乘:cheng ,除:chu ,
创建好一个target ,按照OC多文件开发的模式,创建好.h和.m的双文件
代码如下:
1.在.h的文件中:
#import <Foundation/Foundation.h>
@interface Calculator : NSObject { @public int _num1; int _num2; float _result;
} -(void)add; -(void)jian; -(void)cheng; -(void)chu; @end
2.在.m的实现文件中:
#import "Calculator.h"
@implementation Calculator -(void)add{ _result=_num1+_num2; } -(void)jian{ _result=_num1-_num2; } -(void)cheng{ _result=_num1*_num2; } -(void)chu{ _result=_num1/(float)_num2; } @end
3.在main.m的文件中来进行复制运算并输出
#import <Foundation/Foundation.h> #include "Calculator.h"
int main(int argc, const char * argv[]) { @autoreleasepool { //进行实现 Calculator * cal=[Calculator new]; //赋值 cal->_num2=10; cal->_num2=3; //调用加法 ——>(*******) [cal add]; NSLog(@"%.2f",cal->_result); } return 0; }
输出结果分别为:[分别在(******)处// 调用加(add);减(jian);乘(cheng);除(chu)]
2015-10-17 15:37:23.299 Calculator[734:29585] 13.00 Program ended with exit code: 0
2015-10-17 15:38:46.807 Calculator[745:30335] 7.00
Program ended with exit code: 0
2015-10-17 15:39:09.429 Calculator[753:30573] 30.00
Program ended with exit code: 0
2015-10-17 15:39:31.037 Calculator[761:30810] 3.333333
Program ended with exit code: 0
大家 相互学习进步哈~
|