静态成员函数设置的目的是为程序中一些变量保值而设定的
定义静态成员函数需要注意的几点
(1)静态成员函数主要用来访问静态数据成员,而不访问非静态成员
(2)静态成员函数是类的一部分而不是对象的一部分。
统计学生的平均成绩代码
#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(1005,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;
}