------
Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
对象与函数参数:
<span style="font-size:18px;">#import <Foundation/Foundation.h>
@interface Car : NSObject
{
int wheels; // 轮子</span>
<span style="font-size:18px;"> int speed; // 速度
}
- (void)run; // 跑方法
@end
@implementation Car
- (void)run
{
NSLog(@"%d个轮子,%d的速度在跑",whells, speed );
}
@end
// 再写一个函数
void test(int w, int s)
{
w = 20;
s = 200;
} /*调用此函数时(只是简单的值传递,wheels和speed的值传给w和s,然//后w和s被赋值为20和200),输出wheels 和speed的值不变 */
void test1(Car *newC)
{
newC->wheels = 5;
} // 调用此指针函数后,wheels的值变为5
int main()
{
Car *p = [Car new];
p->wheels = 4;
p->speed = 250;
test(c->wheels, c->speed);
test1(c);
[p run];
return 0;
}</span>
常见错误:
1、@interface 和@implementation的@end必须分开写
2、方法的声明和实现顺序不能颠倒
3、可以把类的实现放在main的后面,但声明必须放在前面。和函数类似
方法和函数的区别:
1、对象方法都是以‘-’号声明
2、对象方法的声明必须写在@interface和@end之间
对象方法的实现必须写在@implementation和@end之间
3、不能随便将成员当做c中的变量来使用
4、所有对象方法归类/对象所有,
函数:
1、函数能写在文件的任意位置(除了@interface和@end之间),函数归文件。
2、函数调用不依赖于对象(他们没关系)
3、写法和方法不一样
4、函数内部不能直接通过对象的成员变量名访问某个成员变量
/* 学生
成员变量:性别、生日、体重、最喜欢的颜色、狗(体重、毛色。跑、吃)
方法:吃、跑、遛狗(让狗跑)、喂狗(让够吃)
*/
typedef enum
{
SexMan,
SexWoman,
} Sex;
typedef struct
{
int year;
int month;
int day;
} Date;
typedef enum
{
ColcorBlack,
ColcorRed,
ColcorGreen,
} Colcor;
@interface Dog : NSObject // 狗也是一个对象
{
@public
double weight; //体重
Colcor curColcor; // 毛色
}
- (void)eat;
- (void)run;
@end
@implementation Dog
- (void)eat
{
// 每吃一次,体重加1
weight += 1;
NSLog(@"狗吃完这次后的体重是%f", weight);
}
- (void)run
{
<span style="white-space:pre"> </span>// 狗跑一次瘦一斤
weight -= 1;
NSLog(@"狗跑完这次后的体重是%f", weight);
}
@end
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
@public
Sex sex; // 性别
Date birthday; // 生日
double weight; // 体重
Colcor favColcor; // 喜欢的颜色
char *name; // 姓名
Dog *dog; // 对象要用指针
}
- (void)eat;
- (void)run;
- (void)print; // 加一个方法输出学生属性
- (void)liudog;
- (void)weidog;
@end
@implementation Student
- (void)liudog
{
[dog run];
}
- (void)weidog
{
[dog eat];
}
- (void)eat
{
// 每吃一次,体重加1
weight += 1;
NSLog(@"吃完这次后的体重是%f", weight);
}
- (void)run
{
weight -= 1;
NSLog(@"跑完这次后的体重是%f", weight);
}
- (void)print
{
NSLog(@"性别=%d, 喜欢的颜色=%d, 姓名=%s, 生日=%d-%d-%d", sex, favColcor, name, birthday.year, birthday.month, birthday.day ”)
}
@end
int main()
{
Student *s = [Student new];
Dog *d = [Dog new];
d->curColcor = ColcorGreen;
d->weight = 20;
s->dog = d;
s->weight = 50;
s->sex = SexMan;
s->name = "jack";
s->birthday.year = 2011; // s->birthday = {2011, 9, 12};这样写不对
s-> birthday.month = 9;
s-> birthday.day = 12;
/*s->birthday.year = 2011; s-> birthday.month = 9;s-> birthday.day = 12;三个也可以写成
Date d = {2011, 9, 12};
s->birthday = d; */
s->favColcor = ColcorBlack;
[s eat];
[s eat];
[s run];
[s print];
[s weidog];
[s liudog];
return 0;
}