若在类中声明静态成员变量,静态成员变量为所有对象所共享,不属于任何类,存在于静态区 //在类中声明: class test{ public: static int a; }; //初始化静态成员变量 必须在类外初始化静态成员变量(在Public与在Private声明同样在类外直接用类名调用。但在访问的时候private就需要静态成员函数来访问了) int test::a=0; //若静态成员变量在public声明,则可以用A::a直接访问,即静态成员函数与静态成员变量均可以通过类名直接调用,不需要对象 //若静态成员变量在private声明,则需要在类中定义静态成员函数用于访问静态成员
下面是简单的代码测试
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; class student { public: student(int i,double s):id(i),score(s) { count++; a_score+=score; avg=a_score/count; } static void show() //静态成员变量为私有成员,必须定义静态成员函数访问 { cout<<count<<" "<<a_score<<" "<<avg<<endl; } private: int id; double score; static int count; static double a_score; static double avg; }; double student::avg=0.0; int student::count=0; double student::a_score=0.0; int main(int argc, char** argv) { student s1(123,90); student s2(456,100); student::show(); return 0; }