OC的类方法、对象方法和函数

OC语言中的方法和函数是有区别的:类内部叫方法,单独定义的叫函数,定义的格式也不同

类方法:+ (void) 方法名、对象方法:- (void) 方法名、函数:void 函数名(参数列表)

 1 #import <Foundation/Foundation.h>
 2 
 3 void test();//test函数的声明
 4 
 5 //类Person的声明
 6 @interface Person : NSObject
 7 + (void)test;//类方法
 8 - (void)test;//对象方法
 9 - (int)sumWithNum1 : (int)num1 andNum2 : (int)num2;//带参数对象方法的规范定义
10 
11 @end
12 
13 //类Person的实现
14 @implementation Person
15 + (void)test
16 {
17     //类方法中可以通过创建对象调用对象方法
18     Person *pp = [Person new];
19     [pp test];
20     
21     test();
22     NSLog(@"this is +test");
23 }
24 - (void)test
25 {
26     test();
27     //[Person test];//对象方法中可以调用类方法
28     NSLog(@"this is -test");
29 }
30 - (int)sumWithNum1 : (int)num1 andNum2 : (int)num2
31 {
32     return num1 + num2;
33 }
34 @end
35 
36 
37 int main()
38 {
39     
40     Person *p = [Person new];
41     [Person test];
42     [p test1];
43 }
44 
45 //函数的实现
46 void test()
47 {
48     NSLog(@"这是函数");
49 }

结论:1->类方法名,对象方法名,函数名可以一样,他们的调用者不同所以互不影响

   2->函数是不可以调用类方法或者对象方法的

   3->函数可以被类方法和对象方法调用,类方法内部还可以通过创建该类的对象调用对象方法

 

原文地址:https://www.cnblogs.com/cxbblog/p/3705799.html