一、类的声明(student.h)
// Created by yin on 13-5-4.
// Copyright (c) 2013年 yin. All rights reserved.
// .h文件用来声明Student这个类有哪些成员变量和方法
#import <Foundation/Foundation.h>
// @interface代表声明一个类
// :代表继承
@interface Student : NSObject{
//声明的成员变量定义在此大括号中
int age;
}
// 在类的声明文件中,声明的所有方法都是公共方法
// -代表动态方法 +代表静态方法
// 声明的方法,凡是类型,都用()括住
//age的get方法
- (int)getAge;
//age的set方法,方法名后一个:对应一个参数
- (void)setAge:(int)ageNum;
@end
二、类的定义(student.m)
// Created by yin on 13-5-4.
// Copyright (c) 2013年 yin. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Student.h"
//实现student.h声明文件中声明的Student类
@implementation Student
- (void)setAge:(int)ageNum{
age=ageNum;
}
-(int)getAge{
return age;
}
@end
三、Main方法中创建对象并调用set和get方法
// Created by yin on 13-5-3.
// Copyright (c) 2013年 yin. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Student.h"
//导入类的.h声明文件,若导入.m定义文件,则会处方法重复定义链接错误
int main(int argc, const char * argv[])
{
@autoreleasepool {
//1.调用Student从NSObject继承的alloc静态方法来分配内存
Student *stu=[Student alloc];
//2.调用动态方法init进行初始化
stu=[stu init];
//以上两句可以简化为 Student *stu=[[Student alloc] init]
[stu setAge:90];
NSLog(@"age is %d",[stu getAge]);
}
return 0;
}