问题描述
-
一个仓库具有 进货和出货两种操作,每个货物有自己的重量,最后统计仓库的总重量,货物的进与出通过终端进行交互。
-
货物与货物之间通过链表连接,这样便于管理,类似于:
代码
#include "stdafx.h"
#include <iostream>
using namespace std;
class Goods
{
public:
Goods(int w):m_weight(w)
{
next = NULL;
total_weight += m_weight;
cout << "入库了货物重量是:" << m_weight << endl;
}
static int Get_Total()
{
return total_weight;
}
~Goods()
{
total_weight -= m_weight;
cout << "出库了货物重量是:" << m_weight << endl;
}
Goods* next;
private:
int m_weight;
static int total_weight;
};
int Goods::total_weight = 0;
void Buy(Goods* &head, int weight) //进货
{
Goods* new_good = new Goods(weight);
if (head == NULL)
{
head = new_good;
}
else
{
new_good->next = head;
head = new_good;
}
}
void Sale(Goods* &head) //出货
{
if (head == NULL)
{
cout << "仓库中没有货物了" << endl;
return;
}
else //在头部删除
{
Goods* tmp = head;
head = head->next; //当最后一个的时候head->next = NULL, 下次再出货上面条:if (head == NULL)就满足
delete tmp;
}
}
int main(void)
{
cout << "1: 进货" << endl;
cout << "2: 出货" << endl;
cout << "3: 退出" << endl;
int weight;
Goods* head=NULL;
int choice;
cin >> choice;
do
{
switch (choice)
{
case 1:
cout << "请输入货物重量" << endl;
cin >> weight;
Buy(head,weight);
break;
case 2:
Sale(head);
break;
default:
return 0;
}
cout << "当前仓库总重量 : " << Goods::Get_Total() << endl;
cout << endl;
cin >> choice;
} while (choice != 3);
return 0;
}
结果: