静态成员函数的例子:
//某商店经销一种货物。货物购进和卖出时以箱为单位,各箱的重量不一样,因此,
//商店需要记录目前库存的总重量。现在用C++模拟商店货物购进和卖出的情况。
#include"iostream"
using namespace std;
class Goods{
private:
int weight;
static int total_weights;
public:
Goods(int w){
weight=w;
total_weights+=w;
}
~Goods(){
total_weights-=weight;
}
int Weight(){ return weight;}
static int TotalWeight(){ return total_weights; } //注意静态成员函数是静态的
Goods *next; //构建类链表
};
int Goods::total_weights=0;
void purchase(Goods * &f,Goods * &r,int w){
Goods *p=new Goods(w); //析构函数进行增加重量
p->next=NULL;
if(f==NULL) //头指针为空,证明还没有数据
f=r=p;
else{
r->next=p; // 将p放在尾指针指向的下一个位置,
r=r->next; // 尾指针后移
}
}
void sale(Goods *&f,Goods *&r){
if(f==NULL){
cout<<"No any Goods!\n"<<endl;
return;
}
Goods *q=f; // 取出头元素
f=f->next; //头指针后移
delete q;
cout<<"saled!\n"<<endl;
}
int main(){
Goods *front=NULL,*rear=NULL;
int w ,choice;
do{
cout<<"Please choice:\n" ;
cout << "Key in 1 is purchase,\nKey in 2 is sale,\nKey in 0 is over.\n" ;
cin >> choice ;
switch(choice){
case 1: // 键入1,购进1箱货物
{ cout << "Input weight: " ;
cin >> w ; // 从表尾插入1个结点
purchase( front, rear, w ) ;
break;
}
case 2: // 键入2,售出1箱货物
{ sale( front, rear ) ; break ; } // 从表头删除1个结点
case 0:
break ; // 键入0,结束
}
cout << "Now total weight is:" << Goods::TotalWeight() << endl ;
}while(choice);
return 0;
}