代码给你,自己看吧,貌似你没学到分文件开发吧,直接把代码给你整一个文件里了,从上到下依次是子弹类,枪类和士兵类,最后是main函数.看不懂的可以问我
#import <Foundation/Foundation.h>
@interface Bullet : NSObject
@property int bulletCount;
@end
@implementation Bullet
@end
@class Soldier;//防止重复引用
#import"Bullet.h"
@interface Gun : NSObject
@property NSString *size;
-(void)shoot:(Soldier *)soldier andBullet:(Bullet *)bullet;
@end
@implementation Gun
-(void)shoot:(Soldier *)soldier andBullet:(Bullet *)bullet{
NSLog(@"那个叫%@的士兵正在拿着%@枪向前猛烈射击!当前剩余子弹%d",soldier.name,self.size,bullet.bulletCount);
}
@end
@interface Soldier : NSObject
@property NSString *name;
@property Gun *gun;
@property Bullet *bullet;
-(void)fireByGun;
@end
@implementation Soldier
-(void)fireByGun{
if(self.bullet.bulletCount>0){
self.bullet.bulletCount--;
[_gun shoot: self andBullet: self.bullet];
}//将俩对象都声明在自己内部
else{
NSLog(@"都没子弹了还突突个毛线!");
}
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Gun *gun=[Gun new];
Soldier *s1=[Soldier new];
Bullet *b1=[Bullet new];
b1.bulletCount=5;
s1.name=@"如意大师";
gun.size=@"沾有粑粑的M4A1";
s1.gun=gun;//枪给人
s1.bullet=b1;//弹夹给人
[s1 fireByGun];
[s1 fireByGun];
[s1 fireByGun];
[s1 fireByGun];
[s1 fireByGun];
[s1 fireByGun];
}
return 0;
} |