您的位置:首页 > 职场人生

黑马程序员------类和对象

2015-05-20 15:07 399 查看
                                                                                 -----------android培训、java培训、java学习型技术博客、期待与您交流!------------

                                                                                                                                   

                                                                                                                  

类和对象
1类的声明和实现
类是对象的抽象,而对象是类的具体实例。类是抽象的,不占用内存,而对象是具体的,占用存储空间。类是用于创建对象的蓝图,它是一个定义包括在特定类型的对象中的方法和变量

 类的声明(声明对象属性“成员变量”初始化为零)
NSObject,目的是让car这个类具备创建对象的能力
@public可以让外部的指针间接访问对象内部的成员变量
@interface Car :NSObject
{
@public
int wheels;
int speed;
}
@end

1.     类的实现(方法的实现)
@implementation Car
{
}
@end
Int main(  )
{
//利用类创建对象
//在oc中执行一些行为就写上一个中括号[行为执行者,行为名称]
//定义了一个指针变量p,p将来指向的是car类型的对象
//[car new]会创建出一个新对象,并且会返回新对象本身
Car *p = [Car new];
Car *p 1= [Car new];
//给p所指向对象的wheels属性赋值
P→wheels = 4;
p→speed = 200;
P1→wheels = 5;
P1→speed = 300;
Return0;
}
//给p所指向的对象发送一条run消息
[p run]
NSLog(@”学习,科目:%d”, P→wheels, P1→speed,);

对象的行为
只要是oc对象的方法,必须以见好 – 开头
oc方法中任何数据类型都必须用小括号()扩住
oc方法中的小括号()扩住数据类型
(void)run;
{
NSLog(@”学习”);
}
@end

方法与成员变量
 1.类的声明(成员变量,方法的声明)

@interface  person : Nsobject
{
Int age;
Double weight
}
(void)walk;
@end

1.     类的实现
@implementation 类名
(void)walk
{
Nslog(@”唱了一首歌”,age);

}
@end
Int main()
{
Person *p =[person new];
p→age = 10;
p→weight = 30;
Person *p 2=[person new];
P2→age = 20;
P2→weight = 40;
P = p2;

[p2 walk];
return 0;


类跟函数
#import <Foudation/ Foudation .h>
@interface Car : Nsobject
{
Int wheels;
Int speed;
}
-(void)run;
@end
@impiementation Car
-(void)run
{
NSLog(@”%d个杯子,”,wheels)
}
@end
Void test(int w, int s);
{
w=20;
s = 200;
void test1(Car *newC)
{
newC→wheels = 5;
}
}
Int main( )
{
Car *c = [Car new];
c→wheels = 4;
c→speed = 200;
ttest1(c);
[c run];
Return 0;
}

类的合理设计
Typedef enum{
SexMan,
SexWoman
}Sex;
Typedef struct{
Int year;
Int month;
Int day;
}Date;
Typedef enum{
ColorBlack,
ColorRed,
ColorGreen
}Color;

#import <Foundation/ Foundation .h>
@interface Student : NSObject
{
@public
Sex sex;
Date birthday;
double weight;
Color favColor;
Char *name;
}
-	(void)cat;
-	(void)run;
-	(void)print;
@end
@implementation Student
-	(void)print
{
NSLog(@”性别=%d,姓名=%s,生日=5d-%d-%d”,sex);
}
-(void)eat
{
Weight +=1;
NSLog(@”吃完后的体重是%f”,weight);
}
-	(void)run
{
Weight -= 1;
NSLog(@”跑完后的体重是%f”,weight);
}
@end
Int main( )
{
Student *s = [Student mew];
s->weight = 50;
s->sex = SexMan;
Date d = {2015,9,19};
s->birthday = d;
s->name = “jack”;
s->favColor = favColorBlack;
[s eat];
[s eat];

[s run];
[s run];
}
在类外定义函数时,应指明函数的作用域。在成员函数引用本对象的数据成员时,只需直接写数据成员名,这时系统会把它默认为本对象的数据成员。也可以显式地写出类名并使用域运算符

在大多数情况下,主函数中甚至不出现控制结构(判断结构和循环结构),而在成员函数中使用控制结构。

面向对象的程序设计中,最关键的工作是类的设计。所有的数据和对数据的操作都体现在类中。

只要把类定义好,编写程序的工作就显得很简单了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  类和对象