您的位置:首页 > 其它

全局变量和全局静态变量的区别

2015-06-30 22:24 218 查看
1)全局变量是不显式用static修饰的全局变量,全局变量默认是有外部链接性的,作用域是整个工程,在一个文件内定义的全局变量,在另一个文件中,通过extern 全局变量名的声明,就可以使用全局变量。

2)全局静态变量是显式用static修饰的全局变量,作用域是声明此变量所在的文件,其他的文件即使用extern声明也不能使用。

// Book.h
NSString *const bookName = @"Cocoa";

@interface Book : NSObject

@end

// Student.h
extern NSString *bookName;

@interface Student : NSObject

@end

// Student.m
#import "Student.h"

@implementation Student
- (NSString *)description
{
return [NSString stringWithFormat:@"%@", bookName];
}
@end

#import "ViewController.h"
#import "Student.h"
@interface ViewController ()

@end

// viewController.m
@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

Student *s = [[Student alloc] init];
NSLog(@"s = %@", s);
}

// 结果: s = Cocoa

但是如果写成
static NSString *const bookName = @"Cocoa";
再编译就会报错了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: