二、code
>>>Main.m
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;
// 商家對象
// Shop *shop = [Shop new];
// 2.創(chuàng)建槍
// Gun *gp = [Gun new];
// 2.購買手槍
Gun *gp = [Shop buyGun:888];
// 3.創(chuàng)建彈夾
// Clip *clip = [Clip new];
// [clip addBullet];
// 3. 購買彈夾
Clip *clip = [Shop buyClip:88];
// 4.士兵開火
[s fire:gp Clip:clip];
return 0;
}
>>>Soldier
.h
#import <Foundation/Foundation.h>
#import "Gun.h" // 間接拷貝
@interface Soldier : NSObject
{
@public
NSString *_name;
double _height;
double _weight;
}
// 開火,給士兵 一把槍,和彈夾
- (void)fire:(Gun *)g Clip:(Clip *)clip;
@end
.m
#import "Soldier.h"
@implementation Soldier
- (void)fire:(Gun *)g Clip:(Clip *)clip
{
if (g != nil &&
clip != nil){
[g shoot:clip];
}
}
@end
>>>Gun
.h
#import <Foundation/Foundation.h>
#import "Clip.h"
// 多文件開發(fā)中, 要使用誰的.h文件就可以了
// 注意 : 導(dǎo)入的一定是.h文件, 不能是.m文件
// 如果 導(dǎo)入.m文件會報重復(fù)定義錯誤
@interface Gun : NSObject
{
@public
Clip *clip; // 彈夾
}
// 想要射擊,必須傳遞彈夾
- (void)shoot:(Clip *)c;
@end
.m
#import "Gun.h"
@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(@"沒有彈夾 ,請換彈夾");
}
}
@end
>>>Clip
.h
#import <Foundation/Foundation.h>
@interface Clip : NSObject
{
@public
int _bullet;
}
- (void)addBullet;
@end
.m
#import "Clip.h"
@implementation Clip
- (void)addBullet
{
// 上子彈
_bullet = 10;
}
@end
>>>Shop
.h
#import <Foundation/Foundation.h>
#import "Gun.h"
@interface Shop : NSObject
// 買槍
+ (Gun *)buyGun:(int)monery;
// 買彈夾
+ (Clip *)buyClip:(int)monery;
@end
.m
#import "Shop.h"
@implementation Shop
+ (Gun *)buyGun:(int)monery
{
// 1.創(chuàng)建一把槍
Gun *g = [Gun new]; // 通過 new 創(chuàng)建出來的對象 存儲在堆中,堆中的數(shù)據(jù) 不會自動釋放
// 2.返回一把槍
return g;
}
// 買彈夾
+ (Clip *)buyClip:(int)monery
{
// 1.創(chuàng)建彈夾
Clip *clip = [Clip new];
[clip addBullet]; // 添加子彈
// 2.返回彈夾
return clip;
}
@end
image.png
image.png
image.png