class Cat { public: Cat(int age):itsAge(age){HowManyCats++;} virtual ~Cat(){HowManyCats--;} virtual int getAge(){return itsAge;} virtual void setAge(int age){itsAge=age;}; static int HowManyCats; private: int itsAge; }; // int Cat::HowManyCats=0; //对静态成员数据如此赋值 int main() { const int maxCats =5; int i; Cat *catHouse[maxCats]; for(i=0; i<maxCats; i++) catHouse[i]=new Cat(i); for(i=0; i<=maxCats; i++) { cout<<"there are "<<Cat::HowManyCats<<" cats left.\n"; if(!Cat::HowManyCats) break; cout<<"delete the cat which is "<<catHouse[i]->getAge()<<" years old."<<endl; delete catHouse[i]; catHouse[i] = 0; } return 0; }
上面程序的错误是定义了静态数据成员,但没有为之赋值!
对于私有静态数据成员:private: static int HowManyCats;
可以用公有的静态成员函数访问:public: static int GetHowMany(){return HowManyCats;},也可以用非静态成员函数访问,用对象调用此成员函数。