静态成员函数的用例

静态成员函数的例子:


//某商店经销一种货物。货物购进和卖出时以箱为单位,各箱的重量不一样,因此,
//商店需要记录目前库存的总重量。现在用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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值