士兵开枪,设计子弹:
类分析:
1.弹夹
属性:口径,子弹数量
2.枪
属性:枪型号
行为:射击
3.士兵
属性:姓名,生命值
行为:开火
实现代码如下:
- #import <Foundation/Foundation.h>
- #pragma mark 弹夹类
- @interface BulletBox:NSObject
- {
- @public
- NSString *_size;
- int _bulletCount;
- }
- @end
- @implementation BulletBox
- @end
- #pragma mark 枪类
- @interface Gun:NSObject
- {
- @public
- NSString *_size;
- }
- -(void) shoot:(BulletBox *)bulletbox;
- @end
- @implementation Gun
- -(void) shoot:(BulletBox *)bulletbox{
- if(bulletbox->_bulletCount>0){
- bulletbox->_bulletCount--;
- NSLog(@"\n开枪射击,嘭...(枪的型号:%@,子弹口径:%@,剩余子弹:%d)",_size,bulletbox->_size,bulletbox->_bulletCount);
- }else{
- NSLog(@"\n没有子弹了,请更换弹夹!!");
- }
- }
- @end
- #pragma mark 士兵类
- @interface Soldier:NSObject
- {
- @public
- NSString *_name;
- int _life;
- }
- -(void) fire:(Gun *)gun and:(BulletBox *)bulletbox;
- @end
- @implementation Soldier
- -(void) fire:(Gun *)gun and:(BulletBox *)bulletbox{
- [gun shoot:bulletbox];
- }
- @end
- #pragma mark -
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- //实例化弹夹
- BulletBox *bulletbox = [BulletBox new];
- bulletbox->_size = @"0.5mm";
- bulletbox->_bulletCount = 5;
-
- //实例化枪
- Gun *gun = [Gun new];
- gun->_size = @"AK47";
-
- //实例化士兵
- Soldier *soldier = [Soldier new];
- soldier->_name = @"卫龙";
- soldier->_life = 100;
- //连开7枪
- [soldier fire:gun and:bulletbox];
- [soldier fire:gun and:bulletbox];
- [soldier fire:gun and:bulletbox];
- [soldier fire:gun and:bulletbox];
- [soldier fire:gun and:bulletbox];
- [soldier fire:gun and:bulletbox];
- [soldier fire:gun and:bulletbox];
-
-
- }
- return 0;
- }
复制代码 运行结果:
2015-10-09 22:30:37.395 3-OC对象作为方法的参数连续传递[791:27789]
开枪射击,嘭...(枪的型号:AK47,子弹口径:0.5mm,剩余子弹:4)
2015-10-09 22:30:37.396 3-OC对象作为方法的参数连续传递[791:27789]
开枪射击,嘭...(枪的型号:AK47,子弹口径:0.5mm,剩余子弹:3)
2015-10-09 22:30:37.396 3-OC对象作为方法的参数连续传递[791:27789]
开枪射击,嘭...(枪的型号:AK47,子弹口径:0.5mm,剩余子弹:2)
2015-10-09 22:30:37.396 3-OC对象作为方法的参数连续传递[791:27789]
开枪射击,嘭...(枪的型号:AK47,子弹口径:0.5mm,剩余子弹:1)
2015-10-09 22:30:37.396 3-OC对象作为方法的参数连续传递[791:27789]
开枪射击,嘭...(枪的型号:AK47,子弹口径:0.5mm,剩余子弹:0)
2015-10-09 22:30:37.396 3-OC对象作为方法的参数连续传递[791:27789]
没有子弹了,请更换弹夹!!
2015-10-09 22:30:37.396 3-OC对象作为方法的参数连续传递[791:27789]
没有子弹了,请更换弹夹!!
结果分析:
bulletbox对象作为参数传递给了fire方法,通过fire方法又传递给了方法shoot方法。实现了对象作为方法参数的连续传递。
|
|