现在的位置: 首页 > 综合 > 正文

c/c++—–static关键字

2013年10月27日 ⁄ 综合 ⁄ 共 580字 ⁄ 字号 评论关闭

    static即静态的之意。

    在c语言中,我们可以用static将一个全局变量固定在某文件使用,也可以在一个局部函数定义static变量,比如统计该函数被调用的次数。

  在c++语言中,在包含前者的情况下,在类里面pulic变量使用static关键字,表示该变量在实例化(即对象创建)之前就已经占有空间,在pulic函数前面使用static,则表示该函数可以在外部使用类名加函数名称访问。

 示例:

#include<iostream>
using namespace std ; 
class Test{
public:
	Test()
	{ 
		total++;
	}
	static int total ;
	static void print()
	{
		cout<<"print"<<endl ;
	}
	void  bar()
	{
		cout<<"visit "<<total <<endl ;
	}
};
int  Test::total = 3 ;//静态成员初始化
void  foo()
{
	static  int num = 0 ;
	num++ ;
	cout<<num<<endl ;
}
int main(int argc, char* argv[])
{
    Test a , b , c ;
	cout<<Test::total ;  //外部访问total
	Test::print();  //外部访问print
	foo();  //调用3次
	foo();
	foo();
	a.bar();  //成员函数内部访问
	return 0;
}

抱歉!评论已关闭.