C/C++中的static

C中的static

static是用来修饰变量和函数的

  1. 修饰局部变量
  2. 修饰全局变量
  3. 修饰函数

1.修饰局部变量

static修饰局部变量改变了变量的生命周期,让静态局部变量出了作用域依然存在,到程序结束,生命周期才 结束。
例如:

//代码1 
#include <stdio.h> 
void test() 
{    
	int i = 0;    
	i++;    
	printf("%d ", i); 
} 
int main() 
{    
	for(i=0; i<10; i++)    
	{        
		test();    
	}    
	return 0; 
} 
//代码2 
#include <stdio.h> 
void test() 
{    
	static int i = 0;    
	i++;   
	printf("%d ", i); 
} 
int main() 
{    
	for(i=0; i<10; i++)    
	{        
		test();    
	}    
	return 0; 
}

对比代码1和代码2的效果理解static修饰局部变量的意义。

2.修饰全局变量

一个全局变量被static修饰,使得这个全局变量只能在本源文件内使用,不能在其他源文件内使用

//代码1 
//add.c 
int g_val = 2018; 
//test.c 
int main() 
{   
	printf("%d\n", g_val);    
	return 0; 
}
 
//代码2 
//add.c 
static int g_val = 2018; 
//test.c 
int main() 
{    
	printf("%d\n", g_val);    
	return 0; 
}

代码1正常,代码2在编译的时候会出现连接性错误

3.修饰函数

一个函数被static修饰,使得这个函数只能在本源文件内使用,不能在其他源文件内使用。

//代码1 
//add.c 
int Add(int x, int y) 
{    
	return c+y; 
} 
//test.c 
int main() 
{    
	printf("%d\n", Add(2, 3));    
	return 0; 
}
 
//代码2 
//add.c 
static int Add(int x, int y) 
{    
	return c+y; 
} 
//test.c 
int main() 
{    
	printf("%d\n", Add(2, 3));    
	return 0; 
}

代码1正常,代码2在编译的时候会出现连接性错误.

C++中的static

1.静态成员

&

2.静态函数

C++继承了C中static的用法, 由于C++加入了类, 故C++中, 除了C语言中的用法, 还包含两个方面:

  1. 类的成员带static—>静态成员
  2. 类的函数带static—>静态方法

    例:实现一个类,计算中程序中创建出了多少个类对象
在这里插入代码片
class A 
{ 
public:    
	A() 
	{
		++_scount;
	}    
	A(const A& t) 
	{
		++_scount;
	}    
	static int GetACount() 
	{ 
		return _scount;
	} 
private:    
	static int _scount; 
};
 
int Test::_count = 0;
 
void TestA() 
{    
	cout<<A::GetACount()<<endl;    
	A a1, a2;    
	A a3(a1);    
	cout<<A::GetACount()<<endl; 
}

完.

发布了53 篇原创文章 · 获赞 46 · 访问量 7226

猜你喜欢

转载自blog.csdn.net/new_bee_01/article/details/102807994