標籤:
//// Student.h// OOP//// Created by acgity on 16/5/16.// Copyright © 2016年 acgity. All rights reserved.//#import <Foundation/Foundation.h>typedef enum { male,female} SEX;@interface Student : NSObject{ @public NSString *_name; int _age; SEX _sex;}+(void)walk;-(void)talk;-(instancetype)init;-(instancetype)initWithName:(NSString *)name withAge:(int)age withSex:(SEX)sex;@end
//// Student.m// OOP//// Created by acgity on 16/5/16.// Copyright © 2016年 acgity. All rights reserved.//#import "Student.h"@implementation Student-(instancetype)init{ self = [super init]; if(self != nil){ self -> _name = @"acgity"; self -> _age = 23; self -> _sex = female; } return self;}-(instancetype)initWithName:(NSString *)name withAge:(int)age withSex:(SEX)sex{ self = [super init]; if(self != nil){ self->_name = name; self->_age = age; self->_sex = sex; } return self;}-(void)talk { NSString *flag = self->_sex == male ? @"girl" : @"boy"; NSLog(@"Hi,I‘m a %@ named %@ %d years old...",flag,_name,_age);}+(void)walk { NSLog(@"I‘m walking now...");}@end
//// main.m// OOP//// Created by acgity on 16/5/16.// Copyright © 2016年 acgity. All rights reserved.//#import <Foundation/Foundation.h>#import "Student.h"int main(int argc, const char * argv[]) { Student *df = [[Student alloc] init]; [df talk]; [Student walk]; Student *ini = [[Student alloc] initWithName:@"tony" withAge:32 withSex:male]; [ini talk]; [Student walk]; return 0;}
2016-05-16 18:46:34.287 OOP[3140:120047] Hi,I‘m a boy named acgity 23 years old...
2016-05-16 18:46:34.288 OOP[3140:120047] I‘m walking now...
2016-05-16 18:46:34.288 OOP[3140:120047] Hi,I‘m a girl named tony 32 years old...
2016-05-16 18:46:34.288 OOP[3140:120047] I‘m walking now...
Program ended with exit code: 0
Objective-c 類 方法聲明 初始化及調用