转载:http://blog.csdn.net/chaoyuan899
首先新建一个基于命令行的project,命名为“构造函数”,再新建一个Studnet类(怎样新建看前一篇),接下来是代码的编写,需要注意和说明的都写在注释里了。
Student.h
- //
- // Student.h
- // 构造方法
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Student : NSObject
- {
- int _age;
- int _no;
- }
- - (void)setAge:(int)age;
- - (void)setNo:(int)no;
- - (int)age;
- - (int)no;
- - (id)initWithAge:(int)age andNo:(int)no;
- @end
Student.m
- //
- // Student.m
- // 构造方法
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import "Student.h"
- @implementation Student
- -(void)setAge:(int)age
- {
- _age = age;
- }
- - (void)setNo:(int)no
- {
- _no = no;
- }
- - (int)age
- {
- return _age;
- }
- - (int)no
- {
- return _no;
- }
- //实现构造方法,构造方法最好以 init 开头
- - (id)initWithAge:(int)age andNo:(int)no
- {
- self = [super init];//调用父类的构造方法
- //判断self是否为nil
- if(self)
- {
- _age = age;
- _no = no;
- }
- return self;
- }
- @end
main.m
- //
- // main.m
- // 构造方法
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "Student.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- // insert code here...
- Student *stu = [[Student alloc] init];
- [stu initWithAge:15 andNo:2];
- NSLog(@"age is %i and no is %i",[stu age], [stu no]);
- [stu release];//Don't forget this!
- }
- return 0;
- }
我们知道 %i 是输出整型变量,%p是输出地址,,在object c 中 %@ 很常见,它的作用是输出一个object c 对象,当用到%@时,它会调用父类的description函数,对上面的代码做如下改动:
student.h 不变
student.m 增加以下代码
- //%@代表打印一个对象
- //当使用 %@ 打印一个对象的时候会调用这个方法,以下对这个方法进行重写
- - (NSString *)description{
- NSString *str = [NSString stringWithFormat:@"age is %i and no is %i",self.age, self.no];
- return str;
- }
main.m 增加这一句
- //NSLog(@"age is %i and no is %i",[stu age], [stu no]);
- NSLog(@"stu %@",stu);
输出还是跟之前的一样,如下:
2013-08-25 10:35:19.590构造方法[3042:303] stu age is 15 and no is 2
1.object c 变量的命名习惯是以“_”开头的,在编写变量的时候尽量遵循该习惯。