变量初始化问题
当局部变量被定义时,系统不会自动对其初始化;
当全局变量被定义时,系统会初始化为下列值:
| 数据类型 | 
初始化默认值 | 
| int | 
0 | 
| float | 
0 | 
| double | 
0 | 
| char | 
‘\0’ | 
| pointer | 
NULL | 
C++储存类
- auto
 
- static
 
- extern
 
- register
 
- mutable
 
- thread_local
 
static储存类
用于指示编译器在程序的生命周期内保持局部变量的存在,而不需要每次在它进入和离开作用域时进行创建和销毁。
- static修饰局部变量,可以在函数调用之间保持局部变量的值
 
- static修饰全局变量,会使变量的作用域限制在生明它的文件内
参考 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | #include<iostream> using namespace std;
  static int count=10;  
  void func() { 	static int i=5;   	i++; 	cout<<"变量i为:"<<i; 	cout<<",变量count为:"<<count<<endl; } int main() { 	while(count--) 	{ 		func(); 	} 	return 0; }
   | 
 

extern储存类
用于提供一个全局变量的引用,全局变量对所有的程序文件都是可见的。使用extern时,对于无法初始化的变量,会把变量名指向一个之前已经定义过的存储位置。
当有多个文件且定义了一个就可在其他文件中使用的全局变量或函数时,可以在其他文件中使用extern来得到已定义的变量或函数的引用。
C++引用
引用变量是一个别名。它是某个已存在的变量的另一个名字。一旦把引用初始化为某个变量,就可以使用该引用名称或变量名称来指向变量
引用与指针的差别
- 不存在空引用,引用必须连接到一块合法的内存。
 
- 一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
 
- 引用必须在创建时被初始化。指针可以在任何时间被初始化。
 
引用可以当成变量附属在内存的第二个标签
int i;
//为i声明一个引用变量
int& r=i;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   | #include<iostream> using namespace std;
  int main() { 	int i; 	double d;
  	 	int& r=i; 	double& s=d;
  	i=3; 	cout<<"Value of i:"<<i<<endl; 	cout<<"Value of i reference::"<<r<<endl;
  	d=5.20; 	cout<<"d= "<<d<<endl; 	cout<<"Value of d reference:"<<s<<endl;
  	return 0; }
   | 
 

用引用做函数形参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   | #include<iostream> using namespace std;
  void swap(int& x,int& y) { 	int temp; 	temp = x; 	x = y; 	y = temp; }
  int main() { 	int a,b; 	cin>>a>>b; 	cout<<"a="<<a<<" "<<"b="<<b<<endl; 	swap(a,b); 	cout<<"after exchange:"<<endl; 	cout<<"a="<<a<<" b="<<b<<endl; 	return 0;
  }
   | 
 

引用做返回值
当函数返回一个引用时,则返回一个指向返回值的隐式指针。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | #include<iostream> #include<ctime> using namespace std;
  int vals[]={1,2,3,4,5};
  int& setValues(int i) { 	return vals[i]; }
  int main() { 	cout<<"before change:"<<endl; 	for(int i=0;i<5;i++) 	{ 		cout<<vals[i]<<" "; 	}
  	setValues(1)=520;    	setValues(3)=1314;  
  	cout<<endl<<"after change:"<<endl; 	for(int i=0;i<5;i++) 	{ 		cout<<vals[i]<<" "; 	} 	return 0; }
   | 
 
