#import <Foundation/Foundation.h>
#pragma mark 子弹类的声明
@interface Bullet:NSObject
{
@public
NSString *_size;
int _bulletCount;
}
@end
#pragma mark 子弹类的实现
@implementation Bullet
@end
#pragma mark 枪类声明
@interface Gun:NSObject
{
//实例变量
@public
NSString *_size; //枪的型号
}
//枪的行为
-(void)shoot:(Bullet *) bullet;
@end
#pragma mark 枪类实现
@implementation Gun
//枪射击的方法的实现
-(void)shoot:(Bullet *) bullet{
//判断子弹数>0
//子弹对象(弹夹)中的子弹的个数
if(bullet->_bulletCount>0){
//子弹数-1
bullet->_bulletCount --;
NSLog(@"啪啪啪...枪在射击...剩余子弹:%d",bullet->_bulletCount);
}else{
//如果子弹数<0 提示没子弹了
NSLog(@"没子弹了,请换子弹");
}
}
@end
#pragma mark 士兵类声明
@interface Soldier:NSObject
{
@public
NSString *_name;
int life;
int level;
// Gun *_gun;
}
//行为
-(void)fireByGun:(Gun *) gun andBullet:(Bullet *)bullet;
@end
#pragma mark 士兵类实现
@implementation Soldier
-(void)fireByGun:(Gun *) gun andBullet:(Bullet *)bullet{
//让枪装上子弹,然后射击
//子弹作为参数传递给射击的方法
[gun shoot:bullet];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建一个士兵对象
Soldier *s = [Soldier new];
s->_name = @"三多";
s->life = 98;
s->level = 2;
//创建枪的对象
Gun *gun = [Gun new];
gun->_size = @"小米加步枪";
//创建子弹
Bullet *myBullet = [Bullet new];
myBullet->_size = @"5mm口径";
myBullet->_bulletCount = 3;
[s fireByGun:gun andBullet:myBullet];
[s fireByGun:gun andBullet:myBullet];
[s fireByGun:gun andBullet:myBullet];
[s fireByGun:gun andBullet:myBullet];
}
return 0;
}
|
|