Développement OC - la portée des variables membres (25)

Un aperçu

Les variables locales et globales ont leur propre étendue, et les variables membres ne font pas exception. Il existe quatre types de variables membres:

  • @private: accessible uniquement directement dans l'implémentation @implementation de la classe courante
  • @protected: accessible directement dans l'implémentation de la classe et de la sous-classe actuelles @implementation
  • @public: accès direct de n'importe où
  • @package: Le même "système (framework)" est accessible, entre @private et @public

Démonstration à deux portées

2.1 Relations inter-classes

  • La classe personne hérite de NSObject
  • Étudiant hérité de Person

2.2 Déclaration de variable dans le fichier d'en-tête Person.h

#import <Foundation/Foundation.h>
@interface Person : NSObject
{
    int _no;
    
    @public
    int _age;
    
    @private
    int _height;
    
    @protected
    int _weight;
    
    @package
    double _money;
}
-(void)setHeight:(int)height;
-(int)height;
@end
  • Variables de type par défaut_no
  • variable publique_age
  • privé_height
  • type protégé_weight
  • type d'emballage_money

2.3 Classe d'implémentation Person.m

#import "Person.h"

@implementation Person
-(void)setHeight:(int)height
{
    _height=height;
}
-(int)height
{
    return _height;
}
@end

2.4 Fichier d'en-tête Student.h

#import "Person.h"
@interface Student : Person
-(void)study;
@end

2.5 Implémentation de Student.m

#import "Student.h"

@implementation Student
-(void)study
{
    _no=001; //没有定义,默认protected
    _age=10; //public,都能访问
    //_height=170;//private 只能在当前类访问
    self.height=170;//private 通过点语法访问
    _weight=60;
    _money=100;    
}
@end

2.6 fichier d'entrée main.m

Person *p=[Person new];
//p->no, p->_height,p->_weight //private
p->_money=100;//package属性可以访问
p->_age=10;//public属性可以访问

Trois appels de classe main.m dans le même fichier

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

@implementation Car:NSObject
{
    @public
    int _speed;
    int _wheels;
}
-(void)setSpeed:(int)speed
{
    _speed=speed;
}
-(int)speed
{
    return _speed;
}
@end
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        Person *p=[Person new];
        //p->no, p->_height,p->_weight //private
        p->_money=100;//package属性可以访问
        p->_age=10;//public属性可以访问
        
        Car *car=[Car new];
        car->_speed=200;       
    }
    return 0;
}
Publié 362 articles originaux · 118 éloges · 530 000 vues

Je suppose que tu aimes

Origine blog.csdn.net/Calvin_zhou/article/details/105373466
conseillé
Classement