static成员变量和函数

static成员变量表示在类中是共享存储区域的,即任意一个对象对static成员进行操作都会影响同一类其他对象该成员的值。

同时应当注意的是静态成员变量必须初始化,但是不建议放在构造函数中初始化(因为没构建一个对象就会更改其值),最佳

的初始化方式是在类以外的其他地方使用类访问符"::"进行初始化。

 

例如:

#include<iostream>

using namespace std;

class static_example
{
private:
      static int number;
      int x;
public:
    static_example(){
        number = number + 1;
        x = number;
    }
    ~static_example(){
        number = number - 1;
        x = number;
    }
    void display(){
        cout<<"x = "<<x<<endl;
        cout<<"number = "<<number<<endl;
    }
};

int static_example::number = 0;    //静态成员变量的初始化

void main(void)

{
     static_example e1;
     e1.display();
     static_example e2,e3,e4;
     e2.display();
     e3.display();
     e4.display();
     cin.get();
}

 

输出结果为

x = 1;

number = 1;

x = 2;

number = 4;

x = 3;

number = 4;

x = 4;

number = 4;

 

 

C++中可以编写static成员函数,静态成员函数的好处就是可以不创建类对象也可以调用该成员函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岛上码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值