例子1:
#include <iostream> #include <string> using namespace std; class Student { public: Student() {cnt++;} ~Student() {cnt--;} static int count(void); void showCnt(void) const { cout << "The student cnt: " << count() << endl; } private: static int cnt; }; int Student::cnt = 0;
// 静态成员函数 int Student::count(void) { return cnt; } int main(int argc, char** argv) { const Student Mike; cout << "The student cnt: " << Mike.count() << endl; // const对象调用类的static成员函数 Mike.showCnt(); return 0; }
启示:const对象调用是可以调用类的static成员函数的,但不能调用除const,static以外的类的成员函数。
总结(转载如下)
1. 静态数据成员static data member 是 类的,而不是仅属于某个对象的,该类的所有对象都可以调用它,类也可以调用。对象可调用它,但不是独占。生存期:编译时就分配,程序结束才释放空间。他只能在类体外初始化。作用域:与定义它的类的作用域相同,即与类同在。他的存在是为了对象间的共同交流。
2. 静态成员函数Static member function 是为了调用static data member 而存在。Compile 不为他分配this 指针,所以他不能调用对象 的非static data member。当你非要调用 非Static data member 时,只要 指明对象就行了(因为没有compile 没有为类的static member function 指定 this 指针,所以引用 非静态成员变量时分不清是哪个对象的,当你指明对象来调用不就行了。)