本人是 有一个疑问求指导答

iOS 码拜 8年前 (2016-03-30) 928次浏览
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
    int _age;
    int _height;
}
-(id)initWithAge:(int)age andHeight:(int)height; // 自定义的构造方法,是一个动态方法
- (void)showInfo;   
@end
@implementation Person
// 实现自定义的构造方法
-(id)initWithAge:(int)age andHeight:(int)height  
{
    
//先从父类那初始化 固定模板
    self = [super init];
    if(self !=nil){
    
        _age = age;
        _height = height;
    
    }
    return self;
    
}
-(void) showInfo{
        NSLog(@"name is %d and age is %d",_age, _height);
    
    }
    
@end
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Person *person = [[Person alloc]init];
        //person.age = 20;
        //person.height = 50;
               
        Person *person =[[Person alloc]initWithAge:20 andHeight:180];
        
        [person showInfo];
        
       NSLog(@"age = d% height = d%",person.age , person.height); // 为什么这行会报错啊?
    }
    return 0;
}

NSLog(@”age = d% height = d%”,person.age , person.height); // 为什么这行会报错啊? 说没有定义age height
所以本人后来想了一个办法就是申明一个 showinfo 的方法来调用输出结果
一直还没搞明白为什么? 有好心人帮忙解释一下吗?

解决方案

10

OC中的点语法其实访问属性 getXXX, setXXX的简易用法,题主的代码中显示是没有的,当然报错了。
假如要定义属性,也是有简易的语法可用如下,在 .h 文件中的类定义中加入

@property int age;

5

你只是定义的是Protected域的两个变量,但是没有定义访问的方法,所以不可访问;
正确答案,参照上面其他人的回复~

5

你定义的只能在类的内部使用,参考上面的人的回复,定义为property属性的变量

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明本人是 有一个疑问求指导答
喜欢 (0)
[1034331897@qq.com]
分享 (0)