oc基础复习03-OC的类01

首先要想想面向对象和面向过程

在编程语言中 C是面向过程的 OC是面向对象的(一定要有一切即对象的思想)java也是对象对象的 js lua php是解释性语言(脚本) 不过现在好多都是模拟面向对象思想 也很不错。

 

在OC语言中

1、类的声明

@inteferface 类名:父类

{  

//这里声明类的属性

}

//函数的声明

@end

2、类的实现

@implementation 类名

//函数的实现

@end

现在我们来些一个实例  写一个动物类 Animal 属性weight, sex;方法run

Animal.h文件

 

 1 #import <Foundation/Foundation.h>
 2 //定义动物的性别 枚举类型
 3 typedef enum
 4 {
 5     Mail,
 6     Femail
 7 } Sex;
 8 
 9 @interface Animal : NSObject
10 {
11 @public //定义下面的属性是public
12     float _weight;
13     Sex   _sex;
14 }
15 //无参数
16 -(void)run;
17 
18 
19 @end

 

Animal.m文件

1 #import "Animal.h"
2 
3 @implementation Animal
4 
5 -(void)run
6 {
7     NSLog(@"Animal is running!");
8 }

 

main.m文件

 1 #import <Foundation/Foundation.h>
 2 #import "Animal.h"
 3 
 4 int main(int argc, const char * argv[]) {
 5     @autoreleasepool {
 6         // insert code here...
 7         Animal *animal = [Animal new];
 8         animal->_weight = 90;
 9         animal->_sex = Femail;
10         NSLog(@"Animal's weight is %f and sex is %u",animal->_weight,animal->_sex);
11         [animal run];
12     }
13     return 0;
14 }

 

 

输出结果:

2015-07-01 10:28:37.422 review03[48000:1519074] Animal's weight is 90.000000 and sex is 1

2015-07-01 10:28:37.423 review03[48000:1519074] Animal is running!

 注意:

(1)不能将函数实现写在.h文件里面

(2)成员变量需要写在大括号里面

(3)声明成员变量的时候不允许赋值

在OC中方法和函数的区别

1.对象方法都是使用减号(-)

2.对象方法的声明必须写在@inteferface 和 @end之间

   对象方法的实现必须写在@implemention 和 @end之间

3.对象方法只能有对象来调用

4.对象方法归类\对象所有

函数:

函数是能写在文件中的任意位置 函数归文件所有

函数调用不依赖对象

函数内部不能通过成员变量名去访问其它对象的成员变量

posted @ 2015-07-01 10:32  greenboy1  阅读(206)  评论(0编辑  收藏  举报