Part5 数据的共享与保护 5.3类的静态成员

静态数据成员:
  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;
}

 

posted @ 2017-12-01 19:24  LeoSirius  阅读(190)  评论(0编辑  收藏  举报