综合强化练习-仓库货物管理(链表、static、对象)

本文介绍如何使用链表管理仓库中的货物,包括进货和出货操作,并通过终端实现用户交互,最终统计仓库总重量。货物之间通过链表结构连接,方便进行动态管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

  • 一个仓库具有 进货和出货两种操作,每个货物有自己的重量,最后统计仓库的总重量,货物的进与出通过终端进行交互。

  • 货物与货物之间通过链表连接,这样便于管理,类似于:
    在这里插入图片描述

代码

#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;
}


结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值