OC基础--OC中类的声明与定义

OC中设计一个类的步骤:

一、声明类:

  1.用到的关键字--@interface 和 @end

  2.类名

  3.继承NSObject

  4.属性

  5.方法(行为,只需要声明)

二、实现(定义)类

  1.用到的关键字--@implementation 和 @end

  2.实现@interface中声明的方法

  3.类中方法的声明和实现一定注意开头写减号“-”

  4.OC类中的小括号不能乱用,小括号是用来括住类型的!--谨记!

例: 下面的代码中声明和定义的类,类中的方法没有返回值,没有参数

 1    * 实现@interface中声明的方法
 2  */
 3 
 4 #import <Foundation/Foundation.h>
 5 
 6 // 类的声明
 7 @interface Dog : NSObject
 8 // 属性
 9 {
10     @public
11     int speed;
12 }
13 
14 // 只是声明
15 - (void)run;
16 
17 @end // 写完@interface马上写@end
18 
19 // 类的实现(定义)
20 @implementation Dog
21 
22 // 实现run方法
23 - (void)run
24 {
25     NSLog(@"速度为%i的狗跑起来了", speed);
26 }
27 @end
28 
29 int main()
30 {
31     Dog *dog = [Dog new];
32     dog->speed = 100;
33     
34     [dog run];
35     
36     
37     return 0;
38 }

OC中的类的方法名有返回值和参数的情况:

  1.一个参数对应一个冒号

  2.冒号也是方法名的一部分

 1 /*
 2  设计一个计算器类
 3  1.类名:Caculator
 4  2.行为(方法):
 5    * 返回PI:3.14
 6    * 计算某个数值的平方
 7    * 计算两个数值的和
 8  */
 9 
10 #import <Foundation/Foundation.h>
11 
12 // 计算器的声明
13 @interface Caculator : NSObject
14 
15 // 方法的声明
16 - (double)pi; // 方法名pi,返回值类型是double小括号括住类型,无参数
17 
18 // - (double)pi:(int)abc; // 方法名pi:
19 
20 // 一个参数对应一个冒号
21 // 冒号也是方法名的一部分
22 - (double)pingfang:(double)number; // 方法名:pingfang:
23 
24 // 方法名:sumOfNum1:andNum2:--为了增强代码的可读性
25 - (double)sumOfNum1:(double)num1 andNum2:(double)num2;
26 @end
27 
28 
29 int main()
30 {
31     Caculator *ca = [Caculator new];
32     
33     //NSLog(@"PI=%f", [ca pi]);
34     
35     // double d = [ca pingfang:4];
36     
37     // NSLog(@"4的平方=%f", d);
38     
39     double he = [ca sumOfNum1:10 andNum2:5];
40 
41     NSLog(@"10+5=%f", he);
42     
43     
44     
45     Caculator *ca2 = [Caculator new];
46     
47     return 0;
48 }
49 
50 
51 // 计算器的实现
52 @implementation Caculator
53 
54 // 实现@interface中声明的方法
55 - (double)pi
56 {
57     return 3.14;
58 }
59 
60 - (double)pingfang:(double)number
61 {
62     return number * number;
63 }
64 
65 - (double)sumOfNum1:(double)num1 andNum2:(double)num2
66 {
67     return num1 + num2;
68 }
69 
70 @end

OC中函数和OC对象方法的区别:

  1.函数属于整个文件,在文件的任意地方都能调用;对象方法之属于对象,只有对象才能调用对象方法

  2.对象方法只能声明在@interface 和 @end 之间,对象方法只能实现在@implementation 和 @end之间。

  函数的声明和定义可以写在任意地方,函数不能归某个类所有,只属于某个文件。

OC中方法的声明与调用图解:

1.有返回值无参数

方法声明:                       方法调用:

     


2.有返回值并且有一个参数

方法声明:                              方法调用:

    

3.有返回值并且有多个参数

方法声明:                                    方法调用:

    


原文地址:https://www.cnblogs.com/gchlcc/p/5161151.html