c++练习-仓库货物管理

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>

using namespace std;

class Goods
{
public:
    Goods(int weight)
    {
        my_weight = weight;
        total_weight = total_weight + weight;
        cout << "increase weight=" << my_weight << endl;
    }
    void setNext(Goods *point)
    {
        next = point;
    }
    Goods * &getNext()//这种是直接返回返回指针next的引用,这可以直接给私有变量赋值,不是引用返回就不可以给next赋值,只能用next给别的变量赋值
    {
        return next;
    }
    static int getTotalWeight()
    {
        return total_weight;
    }
    ~Goods()
    {
        total_weight = total_weight - my_weight;
        cout << "reduce weight=" << my_weight << endl;
    }
    
private:
    int my_weight;//单个货物的重量
    static int total_weight;//货物总重量
    Goods *next = NULL;
};
int Goods::total_weight = 0;

void buy(Goods * &head, int weight)
{
    Goods *new_goods = new Goods(weight);
    if (head == NULL)
    {
        cout << "-------------------11111111111111" << endl;
        head = new_goods;
        if (head->getNext() == NULL)
        {
            cout << "222222222222222" << endl;
        }
    }
    //如果都用if...if...结构形式的话,前一个if执行完以后head就有值了,所以后一个if也执行了,应用if...else结构
    else
    {
        Goods *point = head;
        head = new_goods;
        head->setNext(point);
    }
}

void sale(Goods * &head)
{
    if (head == NULL)
    {
        cout << "have nothing" << endl;
        return;
    }
    if (head != NULL)
    {
        cout << "---------------------" << endl;
        Goods *point = head;
        head = head->getNext();
        delete point;
    }
}

int main()
{
    Goods *head = NULL;

    while (1)
    {
        cout << "1.buy goods" << endl;
        cout << "2.sale goods" << endl;
        cout << "0.exit" << endl;
        int choice;
        cin >> choice;
        switch (choice)
        {
        case 1://buy
            int weight;
            cout << "please input weight" << endl;
            cin >> weight;
            buy(head, weight);
            break;
        case 2://sale
            sale(head);
            break;
        case 0://exit
            return 0;
        }
        cout << "total_weight=" << Goods::getTotalWeight() << endl;
    }
    
    return 0;
}
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值