题目:某商店经销一种货物,货物购进和卖出以箱为单位,各箱的重量不一样,因此商店需要记录目前库存的总重量,现在用C++模拟商店货物卖出和买进的情况。
#include<iostream>
using namespace std;
class Goods
{
public:
Goods(int w)
{
weight = w;
total_weight += weight;
}//构造函数
~Goods()//析构函数
{
total_weight -= weight;
}
static int Total_weight()
{
return total_weight;
}
Goods *next;类指针
protected:
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 goods" << endl;
}
else
{
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 choose:" << endl;
cout << "key in 1 is purchase,\nkey in 2 is sale\nkey in 0 is over" << endl;
cin >> choice;
switch (choice)//操作选择
{
case 1:
{
cout << "input weight:" << endl;//选择1,购进1箱货物
cin >> w;
purchase(front, rear, w);//从表尾插入一个结点
break;
}
case 2:
{
sale(front, rear); break;//选择2,卖出1箱货物。从表头删除一个结点
}
case 0://键入0,结束。
{
break;
}
}
cout << "now total_weight is:" << Goods::Total_weight() << endl;
}while (choice);
system("pause");
}