类方法和对象方法
类方法
- (+)表示类方法
- 调用方式 1.可以直接调用 2.可以用类名 方法名调用 3.可以用对象名 方法名调用
- 类方法不可以调用实例方法,但是可以创建对象来访问实例方法
- 类方法不可以使用实例变量,但可以使用self
对象方法
- (-)表示对象方法
- 对象方法只能由实例变量来调用
- 对象方法可以访问当前对象的成员变量
- 对象方法的调用格式:【对象名 对象方法名:(参数名)】
#import <Foundation/Foundation.h> @interface Student : NSObject @property double chinese , math ; - (double)average ;//声明一个对象方法 - (void)print ; + (void)textStudent ;//声明一个类方法 @end @implementation Student @synthesize chinese ,math ; - (double)average { return ( chinese + math ) / 2 ; } - (void)print { NSLog(@"语文成绩为:%g , 数学成绩为:%g",chinese , math) ; NSLog(@"平均分为:%g",self.average) ; } //实现一个类方法 + (void)textStudent { Student *stu1 = [[Student alloc]init] ; stu1.chinese = 80 ; stu1.math = 67 ; [stu1 average ] ; [stu1 print] ; } @end int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu = [[Student alloc]init] ; [stu setChinese:78] ; [stu setMath:95] ; [stu average] ; [stu print]; //调用类方法时用类名调用 [Student textStudent] ; } return 0; }
程序运行结果
语文成绩为:78 , 数学成绩为:95
平均分为:86.5
语文成绩为:80 , 数学成绩为:67
平均分为:73.5