/*
某商店经销一种货物,货物的购进和卖出以箱为单位,各箱的重量不一样,
因此商店需要目前库存的总重量。
现在用c++模拟商店货物购进和卖出的情况
*/
#include<iostream>
using namespace std;
//货物类
class Goods{
public:
Goods(int w=0){
this->weight = w;
}
int GetW(){
return weight;
}
Goods *next;
private:
//重量
int weight;
};
//商店类
class Shop{
public:
Shop(int s=0){
this->weights = s;
pHead = NULL;
}
~Shop(){
if (pHead!=NULL)
{
Goods *pCurrent = pHead;
Goods *pNext = NULL;
while (pCurrent){
pNext = pCurrent->next;
delete pCurrent;
pCurrent = NULL;
pCurrent = pNext;
}
}
weights = 0;
}
//卖出
void SellOut(){
if (pHead==NULL)
{
cout << "商店里已经没有货物了!" << endl;
}
else{
//队列 先进先出
Goods *pCurrent = pHead;
pHead = pHead->next;
delete pCurrent;
}
}
//购进
void Purchase(Goods *&pin){
if (pHead==NULL)
{
//插入第一箱货物
pHead = pin;
weights += pin->GetW();
}
else{
Goods *pCurrent = pHead;
while (pCurrent->next){
pCurrent = pCurrent->next;
}
pCurrent->next = pin;
weights += pin->GetW();
}
}
//查询货物重量
int GetWeight(){
return weights;
}
private:
int weights;
Goods *pHead;
};
void protectA(){
Shop *sp = new Shop();
int indexover = 1;
while (indexover){
int num = 0;
int w = 0;
cout << "请输入操作:" << endl;
cout << "1购进货物" << endl;
cout << "2卖出货物" << endl;
cout << "3查看现有货物重量" << endl;
cout << "按任意键退出" << endl;
cin >> num;
switch (num)
{
case 1:
cout << "请输入货物的重量" << endl;
//备注:在c++中不可以在case语句里定义任意变量,如果非要定义,请外面套上大括号{}
//int ss = 0;
//报错 : error C2360: “ss”的初始化操作由“case”标签跳过
{
cin >> w;
Goods * g1 = new Goods(w);
sp->Purchase(g1);
}
break;
case 2:
{
sp->SellOut();
}
break;
case 3:
cout << "现有货物的重量是" << sp->GetWeight() << endl;
break;
default:
indexover = 0;
break;
}
}
if (sp!=NULL)
{
delete sp;
}
}
void main(){
protectA();
system("pause");
}