#include <iostream> using namespace std; class Test { public: Test():x(0), y(0) { cnt++; } int x; int y; void print() const; static int cnt; static void print_s(); //靜態成員函數不能夠設置為const函數 ( static member function cannot have cv qualifier??? cv 限定符 即 const and volatile) }; int Test::cnt = 0; //靜態成員變量的初始化 void Test::print_s() { cout<<cnt<<" object(s) has(have) been created"<<", visited by print_s function"<<endl; } void Test::print() const { cout<<"x = "<<x<<" y = "<<y<<endl; } int main() { int Test::*ptr; //聲明指向類非靜態成員變量的指針 void (Test::*print_p)() const; //聲明指向類非靜態成員函數的指針 print_p = &Test::print; //賦值 ptr = &Test::x; //賦值 Test a; a.*ptr = 1; //調用 (a.*print_p)(); //調用,前面的括號不能掉(運算符的優先級) int *ptr_1 = &Test::cnt; //聲明和初始化指向類靜態成員變量的指針 cout<<*ptr_1<<" object(s) has(have) been created"<<", visited by pointer"<<endl; //通過指針訪問靜態成員變量 Test::print_s(); //通過靜態成員函數訪問靜態成員變量 return 0; }