//学生人数统计
#include<iostream> using namespace std; class Student { private: static int count; //静态数据成员,学生的人数 int unm; int name; int age; public: Student(int n,string nam,int a):num(n),name(nam),age(a){++count;} ~Student(){--conunt;} int getCount(){return const;} }; int Student::count=0; //只能在类外初始化 int main() { Student stu1(1001,"he",40); cout<<stu1.getCount()<<endl; //1 Student *pt=new Student(1001,"you",20); cout<<pt->getCount()<<endl; //2 cout<<stu1.getCount()<<endl; //2 delete pt; cout<<stu1.getCount()<<endl; //1 }静态成员函数为了处理静态数据成员,类的声明函数的方法:
static int getCount();重点::静态成员函数不能处理非静态数据成员:原因 静态成员只有一个空间,各个对象有多个空间
//静态成员函数的使用 #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; } float Student::sun=0; int Student::count=0; //函数的定于 void Student::total() { sum+=score; count++; } float Student::average() { return(sum/count); } int main() { Student stu1[3]= { Student[1000,18,70], Student[1000.18,15]. Student(1005,20,98) }; for(int i=1;i<3;i++) stu[i].total(); cout<<"the average is:"<<Student::average()<<endl; return 0; }