C++模拟商店货物购进和卖出

该博客提出一个问题,某商店经销货物,采购和卖出以箱为单位且各箱重量不同,需利用C++设计实现记录商店采购和卖出情况,同时记录库存总重量。

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

问题:某商店经销一种货物。货物采购和卖出时以箱为单位,各箱重量不一样,请利用C++设计实现商店采购和卖出的情况同时记录库存总重量

Good.h
#pragma once
#include<iostream>

class Goods
{
public:
	Goods* next;
	Goods(int w);
	static int get_total_weight();
	~Goods();
private:
	int weight; //单个物体重量
	static int total_weight; //仓库总重量
};
Good.cpp
#include "Goods.h"

using namespace std;

int Goods::total_weight = 0;
Goods::Goods(int w)
{
	//需要创建一个w的货物,同时总重量+w
	weight = w;
	next = NULL;
	total_weight += w;
	cout << "创建了一个重量为" << weight << "的货物" << endl;
}

int Goods::get_total_weight()
{
	return total_weight;
}

Goods::~Goods() {
	//仓库减少这个货物的重量
	cout << "删除了一箱重量是" << weight << "的货物" << endl;
	total_weight -= weight;
}
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "Goods.h"

using namespace std;

//利用单链表模拟仓库进货出货,并且出货进货操作都在单链表表头进行
void buy(Goods * &head, int w)
{
	Goods* new_goods = new Goods(w);

	if (head == NULL)
	{
		head = new_goods;
	}
	else
	{
		new_goods->next = head;
		head = new_goods; 
	}
}

void sale(Goods*& head)
{
	if (head == NULL) {
		cout << "仓库中已经没有货物了。。" << endl;
		return;
	}

	Goods* temp = head;
	head = head->next;

	delete temp;
	cout << "saled." << endl;
}

int main(void)
{
	int choice = 0;
	Goods* head = NULL;
	int w;

	do {
		cout << "*******" << endl;
		cout << "1 进货" << endl;
		cout << "2 出货" << endl;
		cout << "0 退出" << endl;
		cout << "*******" << endl;
		cin >> choice;

		switch (choice)
		{
		case 1:
			//进货
			cout << "请输入要创建货物的重量" << endl;
			cin >> w;
			buy(head, w);
			break;
		case 2:
			//出货
			sale(head);
			break;
		case 0:
			//退出
			return 0;
		default:
			break;
		}

		cout << "当前仓库的总重量是" << Goods::get_total_weight() << endl;
	} while (1);

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值