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