zoukankan      html  css  js  c++  java
  • OC .(点)与->(箭头)用法区别

    这两天同学总是问OC里.和->的用法区别,当时回答的不是很好,周末查了一下,大概清楚了,在这里记录一笔。
    先看这个例程

     #import <Foundation/Foundation.h>
    
    @interface Test : NSObject
    {
        int temp;    //成员变量
    }
    @end
    @implementation Test
    @end
    
    int main()
    {
    
        Test *t = [[Test alloc] init];
        t->temp = 100;
        NSLog(@"%d",t->temp);
        return 0;
    }
    

    这里

    t->temp = 100;
    NSLog(@"%d",t->temp);
    

    这两行中的t->temp会提示错误,错误说明为instance varviable “temp” is protected。说明是可以访问的,但是因为受保护所以报错,那我们把权限改成public试试。

        @public
        int temp;    //成员变量
    

    结果显示通过,没有错误,说明想法是对的。

    接下来再看看.点语法

     #import <Foundation/Foundation.h>
    
    @interface Test : NSObject
    {
        int temp;    //成员变量
    }
    @end
    @implementation Test
    @end
    
    int main()
    {
    
        Test *t = [[Test alloc] init];
        t.temp = 100;
        NSLog(@"%d",t.temp);
        return 0;
    }
    

    把代码中的t->temp改成lt.temp,发现又会报错,错误说明为Propetery temp not found。。。,也即是说没有找到temp这个属性,当然找不到,因为我们没有定义这个属性。
    这时再在成员变量的声明后加一行代码

    @property int temp;
    

    代码通过,没有错误,说明.点语法是用来访问属性的。再进一步猜想@propetery是声明set、get方法,要是我有set、get方法没有声明@propetery可不可以呢,试试就知道

     #import <Foundation/Foundation.h>
    
    @interface Test : NSObject
    {
        int temp;    //成员变量
    }
    -(void)setTemp:(int)temp;
    -(int)Temp;
    @end
    @implementation Test
    
    -(void)setTemp:(int)temp
    {
    }
    -(int)Temp
    {
    }
    @end
    
    int main()
    {
    
        Test *t = [[Test alloc] init];
        t.temp = 100;
        NSLog(@"%d",t.temp);
        return 0;
    }
    

    偷懒没有实现方法,但是同样没有报错,也就说明证实了猜想。

    至此大概清楚.(点)和->(箭头)的区别了:

    .(点语法)是访问类的属性,本质是调用set、get方法。

    ->是访问成员变量,但成员变量默认受保护,所以常常报错,手动设为public即可解决

  • 相关阅读:
    Codeforces 601B. Lipshitz Sequence(单调栈)
    C++11正则表达式初探
    Codeforces 1051 D.Bicolorings(DP)
    数据库规范——学习小记
    2016 NEERC, Moscow Subregional Contest K. Knights of the Old Republic(Kruskal思想)
    10.2路径
    10.1jihe
    8/9三角形
    8/9,集合的运算
    6.2收费
  • 原文地址:https://www.cnblogs.com/myqiqiang/p/3888843.html
Copyright © 2011-2022 走看看