object-c 学习总结
#import <Foundation/Foundation.h> @interface Person : NSObject { @public NSString *_name; BOOL _gender; @private NSInteger _age; CGFloat _height; CGFloat _weight; } -(id)init; -(instancetype)initWithName:(NSString*)name andGender:(BOOL)gender; -(NSInteger)adder:(NSInteger)x :(NSInteger)y; -(void)setName:(NSString *)name; -(void)setAge:(NSInteger)age; -(void)setName:(NSString *)name andAge:(NSInteger)age; -(void)setName:(NSString *)name :(NSInteger)age; +(void)eat; -(void)sing; -(void)printInfo; @end @implementation Person -(id)init{ _name=@"王五"; _gender=NO; _age = 18; _height = 1.80; _weight = 78; return self; } -(instancetype)initWithName:(NSString *)name andGender:(BOOL)gender{ _name = name; _gender = gender; return self; } -(NSInteger)adder:(NSInteger)x :(NSInteger)y{ NSLog(@"%ld",x+y); return x+y; } +(void)eat{ NSLog(@"吃吃吃..."); } -(void)sing{ NSLog(@"唱唱唱..."); } -(void)setName:(NSString *)name{ _name = name; } -(void)setAge:(NSInteger)age{ _age = age; } -(void)setName:(NSString *)name andAge:(NSInteger)age{ _name = name; _age = age; } -(void)setName:(NSString *)name :(NSInteger)age{ _name = name; _age = age; } -(void)printInfo{ NSLog(@"name:%@, gender:%@, age:%ld, height:%.2f, weight:%.2f",_name, _gender?@"female":@"male", _age, _height, _weight); } @end int main(int argc, const char * argv[]) { Person *person1 = [[Person alloc]initWithName:@"张三" andGender:0]; [person1 printInfo]; [person1 sing]; Person *person2 = [[Person alloc]init]; [person2 printInfo]; [Person eat]; return 0; }
注意:
1. 类的定义一般写在.h头文件中,类中函数的实现可以在.m文件中个性化实现。
2. 静态函数是所有类对象共有的一个函数,只占用一个函数空间,可通过类名调用。
3. 类的init方法是初始化方法,类的实例化和c++很像,都是调用构造方法来实现对实例的初始化。
4. +表示静态函数,-表示动态函数
输出为: