一蔬将、概念
二、代碼
#import <Foundation/Foundation.h>
#pragma mark 類
#pragma mark - 3.彈夾
@interface Clip : NSObject
{
@public
int _bullet;
}
- (void)addBullet;
@end
@implementation Clip
- (void)addBullet
{
// 上子彈
_bullet = 10;
}
@end
#pragma mark - 2.槍
@interface Gun : NSObject
{
@public
Clip *clip; // 彈夾
}
// 注意 : 在企業(yè)開發(fā)中 千萬不要隨意修改一個(gè)方法
- (void)shoot;
// 想要射擊,必須傳遞彈夾
- (void)shoot:(Clip *)c;
@end
@implementation Gun
- (void)shoot:(Clip *)c
{
if (c != nil) { // nul == null == 沒有值
// 判斷有沒有子彈
if (c->_bullet > 0) {
c->_bullet -=1;
NSLog(@"打了一槍 %i",c->_bullet);
}
else
{
NSLog(@"沒有子彈了");
}
}
else
{
NSLog(@"沒有彈夾 ,請(qǐng)換彈夾");
}
}
@end
#pragma mark - 1.士兵
@interface Soldier : NSObject
{
@public
NSString *_name;
double _height;
double _weight;
}
- (void)fire:(Gun *)gun;
// 開火,給士兵 一把槍,和彈夾
- (void)fire:(Gun *)g Clip:(Clip *)clip;
@end
@implementation Soldier
- (void)fire:(Gun *)g
{
[g shoot];
}
- (void)fire:(Gun *)g Clip:(Clip *)clip
{
// 判斷是否 有槍 和子彈
if (g != nil &&
clip != nil) // 這里我覺得不用判斷 clip是不是為空,因?yàn)槲以趕hoot里面已經(jīng)判斷了,如果沒有的話 就提示更換彈夾
{
[g shoot:clip];
}
}
@end
#pragma mark - main函數(shù)
int main(int argc, const char * argv[])
{
// 1.創(chuàng)建士兵
Soldier *s = [Soldier new];
s->_name = @"lyh";
s->_height = 1.71;
s->_weight = 65.0;
// 2.創(chuàng)建槍
Gun *gp = [Gun new];
// 3.創(chuàng)建彈夾
Clip *clip = [Clip new];
[clip addBullet];
// 4.士兵開火
[s fire:gp Clip:clip];
return 0;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者