【问题标题】:"extern const" vs "extern" only仅“extern const”与“extern”
【发布时间】:2011-11-09 21:43:33
【问题描述】:

我见过两种创建全局变量的方法,有什么区别,什么时候使用?

//.h
extern NSString * const MyConstant;

//.m
NSString * const MyConstant = @"MyConstant";

//.h
extern NSString *MyConstant;

//.m
NSString *MyConstant = @"MyConstant";

【问题讨论】:

    标签: objective-c global-variables constants extern


    【解决方案1】:

    前者是常量的理想选择,因为它指向的字符串不能改变:

    //.h
    extern NSString * const MyConstant;
    
    //.m
    NSString * const MyConstant = @"MyConstant";
    ...
    MyConstant = @"Bad Stuff"; // << YAY! compiler error
    
    and
    
    //.h
    extern NSString *MyConstant;
    
    //.m
    NSString *MyConstant = @"MyConstant";
    ...
    MyConstant = @"Bad Stuff"; // << NO compiler error =\
    

    简而言之,默认使用 const(前者)。如果您尝试在以后更改它,编译器会通知您 - 然后您可以代表您确定它是否是一个错误,或者它指向的对象是否可能会更改。这是一个很好的保护措施,可以节省很多错误/令人头疼的问题。

    另一个变体是一个值:

    extern int MyInteger; // << value may be changed anytime
    extern const int MyInteger; // << a proper constant
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多