在头文件中定义static全局变量
1 2 3 4 5 6 7 8 | //标头.h
static int A = 3;
class B
{
public :
static int b;
};
|
1 2 3 | //标头1.h
void test1();
void test2();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //test.cpp
#include<iostream>
using namespace std;
#include"标头.h"
int B::b =3;
void test1()
{
cout<< "test1" <<&A<<endl;
A = 5;
cout<< "A = " <<A<<endl;
cout<< "b = " <<B::b<<endl;
B::b = 5;
cout<< "b = " <<B::b<<endl;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 | //test2.cpp
#include<iostream>
using namespace std;
#include"标头.h"
void test2()
{
cout<< "test2" <<&A<<endl;
cout<< "A = " <<A<<endl;
cout<< "b = " <<B::b<<endl;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 | //source.cpp
#include<iostream>
using namespace std;
#include"标头1.h"
int main()
{
test1();
test2();
return 0;
}
|
结果为:
static变量的作用范围是一个文件 虽然你写在同一个头文件里,但在cpp文件里引用的时候,只是把头文件内容复制进来而已,所以每个cpp里的static变量没有关联
static的作用是 限定 作用域为本文件内 但include 插入扩展 test.cpp和test2.cpp 各自编译为 包含 同名的不同变量A的 test.obj和 test2.obj 当然地址不一样啦
全局变量链接性问题:
1这是外链接全局变量 int i = 3 在其他文件使用时,必须 extern int i; 如果直接在其他文件中 int i = 4; 则会因为重复定义全局变量出错
2这是内链接全局变量, static int i = 3; 其他文件就无法引用了 extern也不行,并且还会覆盖同名的外链接全局变量 其他文件如果你定义 static int i = 4; 其实就是不同的变量了,终归是因为加上static后作用域就变成本文件的了
|