#import <Foundation/Foundation.h>
//分别定义3个类
@interface Bullet : NSObject
{
//定义实例变量
@public
NSString *_model;
int _bulletCount;
}
@end
@implementation Bullet
@end
@interface Gun : NSObject
{
@public
NSString *_size;
}
//声明枪设计的方法
-(void)shoot:(Bullet*)bullet;
@end
@implementation Gun
//实现枪射击方法并判断弹夹中有没有子弹
-(void)shoot:(Bullet *)bullet{
if (bullet->_bulletCount>0) {
//没射击一次,子弹数-1
bullet->_bulletCount--;
NSLog(@"射击,剩余子弹%d",bullet->_bulletCount);
}else{
NSLog(@"没有子弹了");
}
}
@end
@interface Soldier : NSObject
{
@public
NSString *_name;
int _life;
int _level;
}
-(void)shoot:(Gun*)gun andbullet:(Bullet*)bullet;
@end
@implementation Soldier
//调用枪和弹夹
-(void)shoot:(Gun*)gun andbullet:(Bullet*)bullet{
//调用枪中射击方法并给一个弹夹参数
[gun shoot:bullet];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Soldier *s1 =[Soldier new];
s1->_name=@"张三";
s1->_life=20;
s1->_level=3;
Gun *gun= [Gun new];
gun->_size =@"B51";
Bullet *B = [Bullet new];
B->_bulletCount = 2;
for (int i=0; i<2; i++)
[s1 shoot:gun andbullet:B];
}
return 0;
} |
|