【原创】C++变量作用域(三)
星期六那天突然想到关于extern使用的一种情况,如下:
1
////////////a.h/////////////////////
2![]()
3
extern int a;
4![]()
5
/////////////////a.cpp////////////////
6![]()
7
#include "a.h"
8![]()
9
int a = 7;
10![]()
11
///////////////b.cpp//////////////////
12![]()
13
#include "a.h"
14![]()
15
// a = 8;
16![]()
17
//a = a+1; //如果外部变量在这里作为b.cpp的全局变量赋值时会出错
18![]()
19
int func()
20![]()
21
{
22![]()
23
retrun a;
24![]()
25
}
26![]()
27
int _tmain(int argc, _TCHAR* argv[])
28![]()
29
{
30![]()
31
a=a+1; //而当a作为局部变量赋值时却不会报错,且会影响整个项目中a值
32![]()
33
func();
34![]()
35
cout<<a<<endl;
36![]()
37
while(true)
38![]()
39
{
40![]()
41
}
42![]()
43
return 0;
44![]()
45
}
////////////a.h/////////////////////2

3
extern int a;4

5
/////////////////a.cpp////////////////6

7
#include "a.h"8

9
int a = 7;10

11
///////////////b.cpp//////////////////12

13
#include "a.h"14

15
// a = 8;16

17
//a = a+1; //如果外部变量在这里作为b.cpp的全局变量赋值时会出错18

19
int func()20

21
{22

23
retrun a;24

25
}26

27
int _tmain(int argc, _TCHAR* argv[])28

29
{30

31
a=a+1; //而当a作为局部变量赋值时却不会报错,且会影响整个项目中a值32

33
func();34

35
cout<<a<<endl;36

37
while(true)38

39
{40

41
}42

43
return 0;44

45
}至于为什么能作为局部变量而却不能作为全局变量本人确实不解,有待以后的了解。但是如果要以这么一种形式来做变量在多个文件中共享,一定要注意异步读写问题。
文章写得有点粗略,不过没有关系,关键能真正对技术提高有好处。对自己说,加油!
posted on 2009-08-25 01:16 IamEasy_Man 阅读(204) 评论(0) 收藏 举报


浙公网安备 33010602011771号