C++类别之Static成员

类别之static成员
 

類別中宣告為 static 的成員屬於類別,獨立於物件而存在,舉例如下

#include <iostream>
  
class Demo {
public:
    Demo() {
        std::cout << "constructor" << std::endl;
        count++;
    }
    
    static int get_count() {
        return count;
    }
    
private:
    static int count;
};

int Demo::count = 0;

int main() {
    Demo d1;
    std::cout << Demo::get_count() << std::endl;
    Demo d2;
    std::cout << d2.get_count() << std::endl;
    Demo d3;
    std::cout << d3.get_count() << std::endl;
    
    return 0;
}

count 为 static 的资料成员

static int count;
存取宣告为 static 的资料成员得用 static 的成员函数
static int get_count() {
    return count;
}
count 用来计算 Demo 物件建立的次数,这必须在类别定义外先初始化
int Demo::count = 0;
由于 get_count() 为 static 成员函数,因此可以直接用类别名称呼叫
std::cout << Demo::get_count() << std::endl;

结果如下

$ g++ u0909.cpp
$ ./a.out
constructor
1
constructor
2
constructor
3
$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值