1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#import<Fundation/Fundation>
@interface Person:NSObject{
@
private
int
_age;
NSString *_name;
}
-(id) init;
//构造函数
-(
void
) setAge:(
int
)newAge;
-(
void
) setName:(NNString *)newName;
-(
int
) getAge;
-(
void
) dealloc;
@end
@implementation Person
-(id) init{
self = [super init];
//使用super父类的对象,self表示本类的对象
if
(self){
[self setName:@
"无名氏"
];
[self setAge:-1];
NSLog(@
"在构造函数中 name = %@, age = %d"
);
}
return
self;
}
-(
void
) setAge:(
int
)newAge{
_age = newAge;
}
-(
int
) getAge{
return
_age;
}
-(
void
) dealloc{
//析构函数,在对象销毁的时候调用
[super dealloc];
}
@end
int
main(
int
argc,
const
char
*argv[])
{
@autoreleasepool{
Person *xiaoming = [[Person alloc] init];
//带* 号的“xiaoming”既可以看做是指针,也可以是引用
//xiaoming->_age = 20;
[xiaoming setAge:20];
xiaoming->_name = @
"小明"
;
Person *xiaowang = xiaoming;
xiaowang->_age = 22;
int
a = xiaowang->_age;
//a = 22, 而不是20
Person *xiaoli = [[Person alloc] init];
xiaoli->_age = 21;
xiaoli->_name = @
"小李"
;
[xiaoming release];
//调用析构函数
}
return
0;
}
|
类是抽象的概念,对象是一个类的一个具体的表现实体;