OC语言基础之函数与方法

方法


1.对象方法都是以减号 -
2.对象方法的声明必须写在@interface和@end之间
   对象方法的实现必须写在@implementation和@end之间
3.对象方法只能由对象来调用
4.对象方法归类\对象所有

函数


1.函数能写在文件中的任意位置(@interface和@end之间除外),函数归文件所有
2.函数调用不依赖于对象
3.函数内部不能直接通过成员变量名访问某个对象的成员变量

   1:  #import <Foundation/Foundation.h>
   2:   
   3:  @interface Person : NSObject
   4:  @end
   5:   
   6:  @implementation Person
   7:  @end
   8:   
   9:  @interface Car : NSObject
  10:  {// 成员变量\实例变量
  11:      //int wheels = 4; 不允许在这里初始化
  12:      //static int wheels; 不能随便将成员变量当做C语言中的变量来使用
  13:      @public
  14:      int wheels;
  15:  }
  16:   
  17:  - (void)run;
  18:  - (void)fly;
  19:  @end
  20:   
  21:  int main()
  22:  {
  23:      // wheels = 10;
  24:      /*
  25:      Car *c = [Car new];
  26:      c->wheels = 4;
  27:      //run();
  28:  
  29:      [c run];
  30:      */
  31:      
  32:      void test2();
  33:      
  34:      test2();
  35:      
  36:      return 0;
  37:  }
  38:   
  39:  @implementation Car
  40:   
  41:  - (void) fly
  42:  {
  43:      
  44:  }
  45:   
  46:  /*
  47:  void test2()
  48:  {
  49:      NSLog(@"调用了test2函数-%d", wheels);
  50:  }*/
  51:   
  52:  void test()
  53:  {
  54:      NSLog(@"调用了test函数");
  55:  }
  56:   
  57:  - (void)run
  58:  {
  59:      test();
  60:      NSLog(@"%d个轮子的车跑起来了", wheels);
  61:  }
  62:  @end
原文地址:https://www.cnblogs.com/zeyang/p/4318746.html