Part5 數據的共享與保護 5.3類的靜態成員
阿新 • • 發佈:2017-12-01
space clu ace mes 保護 urn public private ret
靜態數據成員:
1 用關鍵字static聲明
2 為該類的所有對象共享,靜態數據成員具有靜態生存期。
3 必須在類外定義和初始化,用(::)來指明所屬的類。
//5-4具有靜態數據成員的Point類 #include<iostream> using namespace std; class Point{ public: Point(int x = 0, int y = 0):x(x), y(y){ count++;//在構造函數中對count累加,所有對象維護共同一個count } Point(Point &p){ x= p.x; y = p.y; count++; } ~Point(){count--;} int getX(){return x;} int getY(){return y;} void showCount(){ cout << " Object count = " << count << endl; } private: int x,y; static int count;//靜態數據成員聲明,用於記錄點的個數 }; int Point::count = 0; int main(){ Point a(4,5); cout << "Point A: " << a.getX() << ", " << a.getY(); a.showCount(); Point b(a); cout << "Point B: " << b.getX() << ", " << b.getY(); b.showCount(); return 0; }
靜態函數成員:
1 類外代碼可以使用類名和作用域操作符來調用靜態成員函數。
2 靜態成員函數主要用於處理該類的靜態數據成員,可以直接調用靜態成員函數。
3 如果訪問非靜態成員,要通過對象來訪問。
//5-5具有靜態數據、函數成員的 Point類 #include<iostream> using namespace std; class Point{ public: Point(int x = 0,int y = 0):x(x),y(y){count++;} Point(Point &p){ x = p.x; y = p.y; count++; } ~Point(){count--;} int getX(){return x;} int getY(){return y;} static void showCount(){ cout << " Object count = " << count << endl; } private: int x,y; static int count; }; int Point::count = 0; int main(){ Point a(4,5); cout << "Point A: " << a.getX() << ", " << a.getY(); Point::showCount(); Point b(a); cout << "Point B: " << b.getX() << ", " << b.getY(); Point::showCount(); a.showCount();//對象也能訪問靜態函數 b.showCount(); return 0; }
Part5 數據的共享與保護 5.3類的靜態成員