C++静态成员函数设计

来源:互联网 发布:cms色彩管理系统 编辑:程序博客网 时间:2024/06/17 14:21
需求:某商店经销一种货物。货物购进和卖出时以箱为单位,各箱的重量不一样,
   因此,商店需要记录目前库存的总重量。
   现在用C++模拟商店货物购进和卖出的情况。 

#include <iostream>using namespace std;class Goods{public:Goods(int w) { weight = w;  total_weight += w; }//购进货物w重量~Goods() { total_weight -= weight; }//售出货物int  Weight() { return  weight; };//返回购进货物总量static  int  TotalWeight() { return  total_weight; }//返回货物总重量Goods *next;//构建类链表private:int  weight;static  int  total_weight;};int  Goods::total_weight = 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;    r = r->next; }}//累减销售货物重量void sale(Goods * & f, Goods * & r){if (f == NULL) { cout << "No any goods!\n";  return; }Goods *q = f;  f = f->next;  delete q;cout << "saled.\n";}void main(){Goods * front = NULL, *rear = NULL;int  w;  int  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;purchase(front, rear, w);          // 从表尾插入1个结点break;}case 2:             // 键入2,售出1箱货物{ sale(front, rear);    break; }       // 从表头删除1个结点case 0:  break;             // 键入0,结束}cout << "Now total weight is:" << Goods::TotalWeight() << endl;} while (choice);}


原创粉丝点击