黑马程序员技术交流社区
标题:
关于类中能不能引用实例变量的问题分享
[打印本页]
作者:
jx836202365
时间:
2015-9-13 22:16
标题:
关于类中能不能引用实例变量的问题分享
类中不能引用实例变量其实是不准确的,类名不能直接引用实例变量,这样说才准确.类只能通过定义一个对象,或者将对象作为参数传进来时,才能使用对象名来引用实例变量.下面有些代码分享给大家
#import <Foundation/Foundation.h>
@interface Student:NSObject
{
@public
int _score;
}
//方法1,可以通过在类方法中定义一个对象,通过对象来访问参数
+(void)study;
-(void)study;
//方法2.可以通过将对象作为参数,通过对象来访问参数
+(void)study:(Student*)student;
@end
@implementation Student
-(void)study{
NSLog(@"什么事情");
}
+(void)study{
Student *student=[Student new];
[student study];
// Student *student =[Student new];
//
// student->_score=10;
// _score = 10;//类方法不能调用实例变量
// NSLog(@"学习成绩 %d",_score);
}
+(void)study:(Student*)student{
student->_score=10;
}
@end
//无论是通过什么方式,都是通过对象来访问参数
int main(){
@autoreleasepool {
//这里引用的方法是类方法+(void)study,类方法中调用对象方法-(void)study
[Student study];
}
return 0;
}
复制代码
作者:
bustle
时间:
2015-9-13 23:10
解释的好好,赞。
作者:
@陈小亮
时间:
2015-9-14 00:04
好棒好棒。。。
作者:
tianzuishiwo
时间:
2015-9-14 00:24
哎,无奈啊,学的时间太短,看不懂啊,请谅解。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2