您的位置:首页 > 移动开发 > Objective-C

OC对象和函数

2015-11-19 22:53 459 查看
#import <Foundation/Foundation.h>

@interface Car : NSObject
{
//成员变量
@public
int wheels;
int speed;
}

- (void)run;
@end

@implementation Car
- (void)run
{
NSLog(@"%d个轮子,速度为%dkm/h的车子跑起来了!",wheels,speed);
}

@end

void test(int w, int s)
{
w = 20;
s = 200;
}

void test1(Car *newC)
{
newC->wheels    =   5;

}

void test2(Car *newC)
{
Car *c2 = [Car new];
c2->wheels  =   5;
c2->speed   =   300;

newC = c2;
newC->wheels    =   6;
}

int main()
{
Car *c = [Car new];
c->wheels   =   4;
c->speed    =   250;

//test(c->wheels, c->speed);
test2(c);

[c run];

return 0;
}


另一个程序

/*
方法和函数的区别:
1.对象方法都是以减号 - 开头
2.对象方法的声明必须写在@interface和@end之间
对象方法的实现必须写在@implementation和@end之间
3.对象方法只能由对象调用
4.对象方法归类\对象所有

函数
1.函数能写在文件中的任意位置(@interface和@end之间除外),函数归文件所有,可在对象方法中调用
2.函数调用不依赖于对象
3.

*/

#import <Foundation/Foundation.h>

//@interface跟@interface也不能嵌套,一对一
@interface Car : NSObject
{
//statoc int wheels;不能随便将成员变量当做C语言中的变量来使用
//int wheels = 4;不允许在这里初始化
@public
int wheels;

}

- (void)run;
- (void)fly;

@end
//@interface跟@implementation不能嵌套
@implementation Car //实现

- (void)run//方法也不能当做C语言的函数使用static
{
NSLog(@"%d个轮子的车跑起来了",wheels);
}

@end

int main()//类的声明一定要在main函数前面,不然无法调用,实现可在main函数后面
{
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Objective-C