学习笔记
带参数的方法
方法声明
#import<Foundation/Foundation.h>
@interface Computer : NSObject
- (int)addNum1:(int)num1 andNum2:(int)num2;
@end
@implementation Computer
//- (返回值类型)方法名:(参数类型)参数名 形参标签:(参数类型)参数名;
- (int)addNum1:(int)num1 andNum2:(int)num2
{
return num1+num2;
}
@end
- 一个参数带一个冒号:
- 值的类型都用小括号()
- 冒号也包含在方法名中,所以上述方法名为addNum1:andNum2:
- 方法名要起得望名生义
方法调用
int main()
{
Computer *c = [Computer new];
NSLog(@"5+2=%d", [c addNum1:5 andNum2:2]);
return 0;
}
在一个方法中调用另一个类的对象
#import<Foundation/Foundation.h>
@interface Dog : NSObject
- (void)eat;
@end
@implementation Dog
- (void)eat
{
NSLog(@"The day is eating!");
}
@end
@interface Student : NSObject
{
@public
Dog *dog;
}
- (void)feedDog;
@end
@implementation Student
- (void)feedDog
{
[dog eat];
}
@end
int main()
{
Student *s = [Student new];
Dog *d = [Dog new];//一开始没有创建Dog对象,以为在初始化Student对象时自动会创建dog对象,导致控制台并没有输出任何信息
s->dog = d;
[s feedDog];
return 0;
}
定义了一个Student类,属性:有一条狗,方法:喂狗,定义了一个Dog类,方法:吃东西。其中Student类的Dog变量由Dog类提供。
类的合理性设计
例如在设计性别这种成员变量时,可以利用枚举类型
typedef enum{
int SexMan,
int SexWoman
}Sex;
在定义时间变量时可以利用结构体
typedef struct{
int year;
int month;
int day;
}Date;