C++学习笔记(1):变量
关于global变量
避免使用全局变量,全局变量的存在破坏了整个程序的模块化,使整个程序的可复用性变差,全局变量可能被多次赋值,一旦全局变量做为条件判断的量,那么一旦全局变量在其他处被更改,那么该条件判断失效程序break到无法预测的结果上
使用全局变量的好的习惯
1、变量的命名,首先要显式的进行命名全局变量,在变量名前面加上g_标志该变量是一个全局变量
2、利用static将变量限制在变量定义的文件内,然后利用函数进行返回该全局变量值,参照下例
原有使用
doubleg_gravity(9.8);// can be exported and used directly in any file
建议使用
staticdoubleg_gravity(9.8);// restrict direct access to this file only
doublegetGravity()// this function can be exported to other files to access the global outside of this file
{
// We could add logic here if needed later
returng_gravity;
}
3、在函数调用时需要使用该变量时尽量避免直接在函数体内进行使用该全局变量,可以将该全局变量作为函数的一个参数传递进去
原有使用:
// This function is only useful for calculating your instant velocity based on the global gravity
doubleinstantVelocity(inttime)
{
returng_gravity*time;
}
建议使用:
// This function can calculate the instant velocity for any gravity value (more useful)
// pass in getGravity() for parameter gravity() if you want to use the global gravity
doubleinstantVelocity(inttime,doublegravity)
{
returngravity*time;
}
局部变量自然只是在变量定义的代码块中有效,当外部有更大作用域的变量时内部变量屏蔽外部变量,个人称之为就近原则
关键字static
作用1
限制全局变量只能在变量定义的文件内使用
作用2
将局部变量的生存期变长,原有的局部变量在代码执行完成之后销毁,加入static之后该变量的值会一直保持,但是不能再别的程序中使用,也就是范围不会提升,只是将该变量的生存期变长了,并且该行在整个程序内只执行一次,多于一次的执行将会被忽略
#include<iostream>
using namespace std;
void doSomething()
{
// int value=1;//变量只是在该函数内部有效
static int value=1;//该表达式在整个程序执行期间只执行一次,并且value变量的存活时间保持到整个程序结束
value++;
cout << value <<endl;
}
int main()
{
doSomething();
doSomething();
doSomething();
cout << value << endl;//在这里引用value 会提示没有undefined value used,也就是说变量域没有提升
return 0;
}
利用作用2可以可以用来产生一个具有唯一性行的输出,比如说标识ID类的
intgenerateID()
{
staticints_itemID=0;
returns_itemID++;
}
|
|