黑马程序员技术交流社区
标题: 对象作为方法的参数连续传递 [打印本页]
作者: Star_FDt78 时间: 2015-12-19 21:36
标题: 对象作为方法的参数连续传递
对象作为方法的参数连续传递
实现功能: 士兵开枪 抢射击子弹
类: 枪类 人类
枪类:
名称: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};
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |