Object-C 代码分为三部分:.h文件、.m文件及调用文件
.h源文件
#import <Foundation/Foundation.h> @interface Student:NSObject { NSString *studentName; NSInteger age; } -(void) printInfo; -(void) setStudentName:(NSString*) name; -(NSString*) studentName; -(NSInteger) age; @end
.m源文件
#import "Student.h" @implementation Student -(void) printInfo { NSLog(@"姓名:%@ 年龄:%d岁",studentName,studentAge); } -(void) setStudentName:(NSString*) name { studentName=name; } -(void)setAge:(NSInteger) age { studentAge=age; } -(NSString*) studentName { return studentName; } -(NSInteger) age { return studentAge; } @end
调用源文件
Student *student=[[Student alloc]init]; //init相当于实例化 [student setStudentName:@"张三"]; [student setAge:10]; [student printInfo]; [student release]; //资源释放
实例方法和构造函数的总结
时间: 2024-10-14 09:41:14