# 第一个OC类的实现

**URL:** <https://www.shiqidu.com/t/topic/342>\
**Category:** 开发调优\
**Tags:** C-C-Obj-C\
**Created:** [2017 年12 月 15 日 07:07 UTC](https://www.shiqidu.com/t/topic/342 "2017-12-15T07:07:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2017 年12 月 15 日 07:07 UTC](https://www.shiqidu.com/t/topic/342/1 "2017-12-15T07:07:37Z")

</div>

```C
#import &lt;Foundation/Foundation.h&gt;  
// 1.类的声明 @interface 类名 @end结尾  
// 类名的首字母必须大写  
@interface Iphone : NSObject  
{  
    // 属性  
    // 类的属性默认是protect修饰的  
    @public  
    float _model;// _开头  
    int _cpu;  
    double _size;  
    int _color;  
}  
// 方法  
// 没有参数不用写() 直接写; 因为()是用来扩住数据类型的  
// OC 中类方法用 + 表示(只能类调用) 对象方法用 - 表示(只能对象调用)  
- (void)about;  
- (char *)loadMessage;  
// OC中有参数要在数据类型前加 :  
// :是方法名称的一部分  
- (int)callPhone:(int)number;  
- (int)sendMessage:(int)number :(char *) content;  
// 为了提高代码阅读性,OC允许给每个参数添加标签  
- (int)sendMessageWithNumber:(int)number andContent:(char *) content;  
@end  
  
// 2.类的实现  
@implementation Iphone  
- (void)about {  
    NSLog(@&quot;型号: %f, cpu: %d, 尺寸: %f, 颜色: %i&quot;, _model, _cpu, _size, _color);  
}  
-(char *)loadMessage {  
    return &quot;电话已欠费，请及时缴费。&quot;;  
}  
- (int)callPhone:(int)number {  
    NSLog(@&quot;打电话给%i&quot;, number);  
    return 1;  
}  
- (int)sendMessage:(int)number :(char *) content {  
    NSLog(@&quot;发短信给%i,内容%s&quot;, number, content);  
    return 1;  
}  
- (int)sendMessageWithNumber:(int)number andContent:(char *) content {  
    NSLog(@&quot;发短信给%i,内容%s&quot;, number, content);  
    return 1;  
}  
@end  
  
int main(int argc, const char * argv[]) {  
    // 通过类创建对象  
    // 在oc中要通过类创建对象 必须给类发送一个消息（好比c语言中调用方法）  
    // 发送消息 在OC中要发送消息先写[类名/对象名 方法名称];  
      
    // 调用new方法后会做三件事  
    // 1.给对象分配内存空间  
    // 2.初始化对象属性  
    // 3.返回对象地址  
      
    // 通过一个Iphone类型的指针接受Iphone对象的地址  
    Iphone *p = [Iphone new];  
    // p 即为Iphone对象  
    // oc中的类本质是结构体  
    p-&gt;_size = 4.5;  
    p-&gt;_model = 7;  
    p-&gt;_cpu = 10;  
    p-&gt;_color = 2;  
    // 打印对象属性  
    NSLog(@&quot;color = %d, model = %f,size = %lf, cpu=%d&quot;, p-&gt;_color, p-&gt;_model, p-&gt;_size, p-&gt;_cpu);  
    // 调用对象方法  
    [p about];  
    char *content = [p loadMessage];  
    NSLog(@&quot;content = %s&quot;, content);  
    [p callPhone:159011053];  
    [p sendMessage:122331 :&quot;hello world&quot;];  
    [p sendMessageWithNumber:12132131 andContent:&quot;good luck&quot;];  
    return 0;  
}  

```

这些`- + []` 真是反人类啊
