#pragma once
#include<iostream>classGoods{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;//利用单链表模拟仓库进货出货,并且出货进货操作都在单链表表头进行voidbuy(Goods *&head, int w){
Goods* new_goods =newGoods(w);if(head ==NULL){
head = new_goods;}else{
new_goods->next = head;
head = new_goods;}}voidsale(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){case1://进货
cout <<"请输入要创建货物的重量"<< endl;
cin >> w;buy(head, w);break;case2://出货sale(head);break;case0://退出return0;default:break;}
cout <<"当前仓库的总重量是"<< Goods::get_total_weight()<< endl;}while(1);return0;}