c++与链表结合

c++货物管理

用链表管理货物,用指针指向这个个链表
定义一个类goods ,定义一个goods *next;
方法buy(head,w),sale(head),在buy中会调用有参数的构造函数,使得总重加上w,并且将新的货物加入链表,sale只使得货物从链表删除即可,因为减重是自动调用析构函数得到的,因为sale中用了delete,会触发析构

// panduan.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include<math.h>

using namespace std;

class Goods {
public:
	Goods()
	{
		weight = 0;
		next = NULL;
		cout << "创建了weight为" << weight << "的货物" << endl;
	}
	Goods(int w)
	{
		//创建一个重量为weight的货物,并且total_weiht要加上这个重量
		weight = w;
		next = NULL;
		total_weight += w;
		cout << "创建了weight为" << weight << "的货物" << endl;
	}
	~Goods()
	{//total_weight减少weihgt的重量
		cout << "xigou删除了重量为" << weight << "的货物" << endl;
		total_weight -= weight;
	}
	static int get()
	{
		return total_weight;
	}
	Goods *next;
private:
	int weight;
	static int total_weight;
};
int Goods::total_weight = 0;
void buy(Goods *&head, int w)
{
	Goods *good = new Goods(w);
	if (head == NULL)
	{
		head = good;

	}
	else {
		good->next = head;
		head = good;
	}
}
void sale(Goods *&head)
{
	if (head == NULL)
	{
		cout << "空空了" << endl; return;
	}
	else {
		Goods *temp = head;
		head = head->next;
		delete temp;

	}

}
int main()
{ 
	int w;
	int choice = 0;
	Goods *head = NULL;
	do {
		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:
			cout << "出货" << endl;
			sale(head);
			break;
		case 0:
			return 0;
		default:
			break;
		}
		cout << "当前仓库的总重量"<<Goods::get() << endl;
	} while (1);
	

	return 0;

}

发布了35 篇原创文章 · 获赞 2 · 访问量 2423

猜你喜欢

转载自blog.csdn.net/weixin_41375103/article/details/104357609