object-c 之面向对象语法

来源:互联网 发布:猫力 黑历史 知乎 编辑:程序博客网 时间:2024/05/11 02:12

今天开始接触object-c语言,感觉他跟C语言有点类似,但是又有很大的不同,尽管它是完全兼容C语言的。我就把我今天学到的东西记录一下吧。
首先,object-c(就简称OC吧) 语言是可以面向对象的,一说到面向对象,我们可能都会想到java语言或者c++中的类的思想,给我的感觉他们都是相通的。它像c++一样拥有头文件(.h文件)与源文件( .m文件 ),在头文件中对类进行声明,在源文件中对类中的具体消息(oc中管方法或者函数叫做消息)进行实现。
在OC中声明一个类我们可以这样写:

#import <Foundation/Foundation.h>@interface Animal : NSObject{@private    int ID;@public    int age;@private    float price;}//构造函数的定义-(id) init;-(id) initWithID:(int)newID;-(id) initWithID:(int)newID andAge:(int)newAge;-(id) initWithID:(int)newID andAge:(int)newAge andPrice:(float)newPrice;//访问设置函数-(void) setID:(int)newID;-(int) getID;-(void) setAge:(int)newAge;-(int) getAge;-(void) setPrice:(float)newPrice;-(float) getPrice;@end

可以看出,oc中,声明类中的成员变量是在花括号里面的,而对类中的一些函数的声明是在花括号之外,并以@end结束声明。
对类中的一些函数是在*.m文件中实现的。如下所示:

////  Animal.m//  Lesson1////  Created by Lee on 7/2/15.//  Copyright (c) 2015 Lee. All rights reserved.//#import "Animal.h"@implementation Animal-(id) init{    self = [super init];    if (self) {        ID = 1;        age = 21;        price = 222.3f;    }    return self;}-(id) initWithID:(int)newID{    self = [super init];    if (self) {        ID = newID;        age = 22;        price = 32.11f;    }    return self;}-(id) initWithID:(int)newID andAge:(int)newAge{    self = [super init];    if (self) {        ID = newID;        age = newAge;        price = 33.33f;    }    return self;}-(id) initWithID:(int)newID andAge:(int)newAge andPrice:(float)newPrice{    self = [super init];    if (self) {        ID = newID;        age = newAge;        price = newPrice;    }    return self;}-(void) setID:(int)newID{    ID = newID;}-(int) getID{    return ID;}-(void) setAge:(int)newAge{    age = newAge;}-(int) getAge{    return age;}-(void) setPrice:(float)newPrice{    price = newPrice;}-(float) getPrice{    return price;}@end

其中-号的含义是指对象的方法。这里需要注意的是凡是以init**** 开始的函数都是某个类的构造函数,并且我们可以看出,这里函数的结构如下:
-(返回值)函数名:(参数类型1)参数名1 标签1:(参数类型2)参数名2 …{
函数内容;
}

例如,声明一个获取设置汽车属性的函数,如下:
- (void) setCar:(int)carID andColor:(string)color andPrice:(float)price;

这个函数的函数名为setCar:andColor:andPrice,形式参数共三个,分别为carID,color,price。这里需要注意一下,如果声明一个函数的时候,请不要将函数的形式参数与该类中的属性名一样,否则,可能会报错。

好了类定义完以后,要去使用该类的对象来完成我们想要实现的一些功能了,oc中实例化对象可以通过alloc来实现。如下:
Animal *animal = [Animal alloc];
这里面[]我觉得是oc所特有的形式,相当于c++或者java中的点的作用,是用来调用对象的函数的。例如,
float price = [animal getPrice];

至此,学会了oc中的类的创建与使用。

0 0