static是用来修饰变量和函数的,基本作用如下;
1.修饰局部变量
//代码1
#include <stdio.h>
#include <stdlib.h>
void Test()
{
int i=0;
++i;
printf("%d ", i);
}
int main()
{
for (int i = 0; i < 7; ++i)
{
Test();
}
return 0;
}
代码1的输出为:1 1 1 1 1 1 1
//代码2
#include <stdio.h>
#include <stdlib.h>
void Test()
{
static int i = 0;
++i;
printf("%d ", i);
}
int main()
{
for (int i = 0; i < 7; ++i)
{
Test();
}
return 0;
}
代码2的输出为:1 2 3 4 5 6 7
比较代码1和代码2,就可以发现:static修饰局部变量,改变了变量的生命周期,让静态变量出了作用域依然存在,到程序结束,生命周期才结束。
2.修饰全局变量
在同一个项目中建立2个源文件 test_1.c 和 test_2.c
//代码1
//test_1.c
int num;
//test_2.c
int main()
{
printf("%d\n",num);
return 0;
}
//代码2
//test_1.c
static int num;
//test_2.c
int main()
{
在编译时,代码1正常,代码2出现连接性错误
结论:一个全局变量被static修饰,改变了变量的作用域,使得这个全局变量只能在本源文件中使用,不能再其他源文件中使用。
3.修饰函数:
static修饰函数:和static修饰全局变量类似,改变了函数的作用域,使得这个函数只能在本源文件中使用,不能再其他源文件中使用。
4.修饰成员变量与成员函数
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n,int a,float s)
:num(n)
,age(a)
,score(s)
{}
void total();
static float average(); //声明静态成员函数
private:
int num;
int age;
float score;
static float sum; //静态数据成员声明
static int count; //静态数据成员声明
};
void Student::total()
{
//非静态成员函数既可以调用非静态成员变量也可调用静态成员变量
sum += score;
count++;
}
float Student::average() //定义静态成员函数
{
return (sum / count);
}
float Student::sum = 0; //静态数据成员初始化
int Student::count = 0; // 静态数据成员初始化
int main()
{
Student stud[3] = { Student(1001,18,70),
Student(1002,19,78),
Student(1003,20,98) };
int n;
cout << "please input the number of students:";
cin >> n;
for (int i = 0; i < n; ++i)
{
stud[i].total();
}
cout << "the average score of" << n << "student is" << Student::average() << endl;
return 0;
}
static修饰的成员变量称为静态成员变量,修饰的成员函数称为静态成员函数
特性:
1.静态成员为所有类所共享,不属于某个具体实例;
2.静态成员变量必须在类外进行定义,定义时不添加关键子static;
(原因:在类内只是声明,并没有定义,即没有分配空间)
3.类静态成员可用类名::静态成员或者对象 . 静态成员来访问;
4.静态成员函数,不能访问任何任何非静态成员;
(原因:因为静态成员函数没有隐藏的this指针)
5.静态成员和类的普通成员一样,也有public,protected,private 3种访问级别, 也可以具有返回值;