#import <Foundation/Foundation.h>
@interface Dog:NSObject
{
char *_name;//创建_name属性是char型(_name=0)
}
-(void)catchThief;
-(void)setName:(char *)name;//_name属性的set方法
@end
@implementation Dog
-(void)catchThief{
NSLog(@"%s狗抓小偷",_name);//访问属性 打印_name狗抓小偷
}
-(void)setName:(char *)name{//用set方法给_name属性创建name
_name=name;//设置_name属性
}
@end
@interface Police : NSObject
{
Dog *_dog;//是一个指针 指向一个Dog类型的对象
}
-(void)setDog:(Dog *)dog;//设置_dog这个指针类型的属性
-(Dog *)getDog;//获取_dog这个指针属性(是Dog类型的指针)
@end
@implementation Police
-(void)setDog:(Dog *)dog
{
_dog=dog;
}
-(Dog *)getDog
{
return _dog;
}
@end
int main()
{
Police *jin =[Police new];//创建警察对象jin
Dog *dahuang =[Dog new];//创建_dog="dahuang"
[dahuang setName:"riben"];//创建_name="riben"得到dahuang="riben"
[jin setDog:dahuang];//狗对象dahuang设置给警察的dog属性
[[jin getDog] catchThief];//getDog返回值(_dog)为[_dog catchThief]实现第10行代码打印
return 0;
} |