对象作为方法的参数连续传递
实现功能: 士兵开枪 抢射击子弹 类: 枪类 人类
枪类: 名称:Gun 属性:型号(_size),子弹个数(_bulletCount) 行为:射击
人类: 名称:Soldier 属性:名字(_name) life level 行为 开枪 #import <Foundation/Foundation.h>
@interface Gun : NSObject {
@public NSString *_size;
} -(void)shoot; @end
@interface Bullet : NSObject { @public NSString *_size; int _bulletCount; } @end
@interface Soldier:NSObject {
@public NSString *_name;
} -(void)fireByGun:(Gun *) gun and :(Bullet *) bullet; @end
@implementation Bullet
@end
@implementation Gun -(void)shoot{
NSLog(@"%@正在射击!!!",_size); } @end
@implementation Soldier -(void)fireByGun:(Gun *) gun and :(Bullet *) bullet{
bullet->_bulletCount = bullet->_bulletCount - 1; if (bullet->_bulletCount>0) {
[gun shoot]; NSLog(@"子弹剩余:%d颗",bullet->_bulletCount);
}else{ NSLog(@"没有子弹了!!!!"); }
} @end
int main() {
Soldier *soldier1 = [Soldier new]; Gun *gun1 = [Gun new]; Bullet *bullet = [Bullet new];
bullet->_bulletCount = 5; gun1->_size = @"AK47"; soldier1->_name = @"Star";
[soldier1 fireByGun:gun1 and:bullet]; [soldier1 fireByGun:gun1 and:bullet]; } 设计一个学生类 属性: 生日 姓名
用结构体作为类的实例变量 typedef struct { int year; int month; int day; }myDate;
@interface Student:NSObject { NSString *_name; myDate *_birthday; } @end
创建类并赋值: Student *stu = [Student new]; stu->_birthday = (myDate){1983,12,5};
|