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中的类的创建与使用。
- object-c 之面向对象语法
- Object-c 面向对象之封装
- object-c面向对象语言
- Object-C面向对象编程
- Object-C 面向对象基础
- Object-c 学习之面向对象的理解
- Java语法之面向对象
- object-c 学习(面向对象)
- Object-c面向对象(上)
- Object-c 面向对象(一)
- Object-c 面向对象(二)
- Object-c 面向对象(三)
- Object-c 面向对象(四)
- Object-C 面向对象的基本特征
- object-c面向对象-成员变量
- 【C#】之面向对象
- Object-C学习之三:Object-C基本语法之一
- Objective-C语法之Object对象的那些事儿(五)
- AutoCompleteTextView实现自动提示
- 20150702_UI之UIView中层的注意事项及MVC练习
- EJB 的转载理解。
- [算法]找数组中和为定值的数组对
- 最值得恐惧的就是恐惧本身,但是你如何能不怕?
- object-c 之面向对象语法
- 关于keil软件仿真时提示no 'read' permission没有读或写权限
- socket编程的一个简单的hello world程序
- spring+thymeleaf
- FP-Growth算法python实现
- 20150702_UI之CALayer简单的两个属性
- 20150702_UI之UITextField使用
- 浏览在线图片
- Tomcat加载类的过程