03. 實例方法和實例變量

實例變量(InstanceVariable)    

    (一個對象會有自己獨特的數據和別的對象不同,這些數據會保存在一些特殊的變量值中,這種變量叫實例變量。類的每個實例(對象)都有一份。)

    用一個類,創建出了一個對象,那我們說這個對象就是此類的一個實例。一個類可以有很多的實例。每一個實例都擁有一份和其他實例不同的數據,這些數據保存在實例變量中。

    實例變量可以定義在interface部分,也可以定義在implementation部分。

創建一個PropertyAndInstanceVariable項目,創建TRFraction類:

#import <Foundation/Foundation.h>


@interface TRFraction : NSObject    //分數類

{

@public        //不保護 ,但實例變量不應該公開,應該用@protected,默認保護,protected自己和子類可以訪問

       //定義實例變量

        int n;    //分子

        int d;    //分母

}

- (void) show;

@end


@implementation TRFraction

-(void) show

{

        NSLog(@"%d/%d", n, d);    //實例變量可直接訪問,不需要寫self,或self->n

}


//main.m中:

 void test1()

{

        TRFraction *f1 = [TRFraction alloc];

        f1->n = 1;

        f1->d = 2;

        [f1 show];

        TRFraction *f2 = [TRFraction alloc];

        f2->n = 2;

        f2->d = 3;

        [f2 show];

}

int main(int argv, const char* argc)

{

        @autoreleasepool{

                test1();

        }

}

//
//  Student.h
//  day02-2
//
//

#import <Foundation/Foundation.h>

@interface Student : NSObject
{
    //實例變量 保存值的
    int _age;
    char _sex;
    float _salary;
}
//給實例變量賦值
//setter 屬性名:int age
-(void)setAge:(int)age; //此age爲參數
-(int)age;
-(void)setSex:(char)sex;
-(char)sex;
-(void)setSalary:(float)salary;
-(float)salary;
@end


//
//  Student.m
//  day02-2
//
//

#import "Student.h"

@implementation Student

{
    int _level; //聲明瞭一個私有的實例變量(放在.m中的實例變量是私有的)
}
-(void)getLevel{  //聲明瞭一個私有的實例方法(放在.m中的實例變量是私有的)
    NSLog(@"getLevel");
}

-(void)setAge:(int)age{
    _age = age;  //屬性和實例變量的關係
    NSLog(@"調用了setter方法");
}

-(int)age{
    return _age;
}

-(void)setSex:(char)sex{
    _sex = sex;
}

-(char)sex{
    return _sex;
}

-(void)setSalary:(float)salary{
    _salary = salary;
}

-(float)salary{
    return _salary;
}

@end


//
//  main.m
//  day02-2
//
//

#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        Student* stu = [Student alloc];
        //[stu setAge:20];
        //NSLog(@"age:%d", [stu getAge]);
        //[stu setSex:'M'];
        //NSLog(@"sex:%c", [stu getSex]);
        //[stu setSalary:6000.1];
        //NSLog(@"salary:%.2f", [stu getSalary]);
        
        stu.age = 18; //自動調用setter方法
        NSLog(@"age:%d", stu.age); //自動調用getter方法
        
        stu.sex = 'M'; //自動調用setter方法
        int sex = stu.sex; //自動調用getter方法
        NSLog(@"sex:%c", sex);
        
        stu.salary = 12000.5; //自動調用setter方法
        NSLog(@"salary:%.2f", stu.salary); //自動調用getter方法
        
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章