静态成员的例子

静态成员的例子,
每个对象都能共享静态成员,并且能访问它,静态成员不会随着对象的产生而分配,或随着对象的消失而丢失.静态数据成员不能在任何函数内分配空间和初始化.

#include "stdafx.h"
using namespace std;

class Account
{
public:
    

    void onePush(int x)
    {
        oneAccount+=x;
        bankSum+=x;
        bankSale++;
        
    }


    void onePop(int x)
    {
        oneAccount-=x;
        bankSum-=x;
        bankSale++;
        
    }
    int oneAccount;

    static int bankSum;//error:static int bankSum=0
    static int bankSale   ;

    static void print()
    {
        cout <<"the sum of the bank: "<<bankSum<<endl;
        cout <<"the times of the trade: " <<bankSale<<endl;
    }
    
};

int Account::bankSum=1000000;//静态数据成员在类声明外分配空间和初始化,
int Account::bankSale=0;//也不能放在main里,


void main()
{

    Account  A;
    Account B;
    A.onePush(100);
    A.onePop(50);
    B.onePush(200);
    B.onePop(20);
    
    A.print();
    B.print();

    cout <<A.bankSum<<" "<<A.bankSale<<endl;//通过对象访问银行里的总数据
    cout <<B.bankSum<<" "<<B.bankSale<<endl;
    cout <<Account::bankSum<<" "<<Account::bankSale<<endl;//直接通过类访问银行里的总数据

}

运行结果:
the sum of the bank: 1000230
the times of the trade: 4
the sum of the bank: 1000230
the times of the trade: 4
1000230 4
1000230 4
1000230 4
Press any key to continue

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值