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;
}

 

转载于:https://www.cnblogs.com/leosirius/p/7944142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值