C++ 第一篇

这篇博客介绍了如何使用C++实现简单的货物管理程序,包括货物类的定义,进货和出货的功能,以及仓库总重量的动态计算。通过一个简单的主程序展示了如何交互操作这些功能。

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

因为找了一份新工作,公司视觉平台是用C++来写的。以前Cognex用的C#。。。。。。。。

现在用C#在公司也就是能写写上位机软件了,哎心塞


别说还挺像的,第一次写。。。。

#include <iostream>
#include <string>
using namespace  std;

class Goods
{
public:
    Goods*next;
    Goods()                        //无参构造函数
    {
        weight_ = 0;
        next = NULL;
    }
    Goods(double weight)        //有参构造函数
    {
        this->weight_ = weight;
        this->next = NULL;
        this->total_weight += weight;
    }
    ~Goods()
    {
        std::cout << "删除一箱重量为:"<<weight_<<"货物"<<endl;
        this->total_weight -= weight_;
    }
    static double Get_total_weight()
    {
        return total_weight;
    }
private:
    double weight_ = 0;            //货物的重量
    static double total_weight;    //仓库的总重量
};
double Goods::total_weight = 0;    //初始化仓库的重量
void Buy(Goods *&head,double weight)//购货
{
    Goods*new_good = new Goods(weight);
    if (head==NULL)
    {
        head = new_good;
    }
    new_good->next = head;
    head = new_good;
}
void Sale(Goods*&head)//出货
{
    if (head==NULL)
    {
        std::cout << "当前仓库中已经没有货物了"<<endl;
        return;
    }
    Goods*temp = head;
    head = head->next;
    delete(temp);//必须是delete,free不能够触发析构函数
}
void main(void)
{
    Goods*head;                    //货物链表头
    do 
    {
        std::cout << "输入 1 为进货" << endl;
        cout << "输入 2 为出货" << endl;
        std::cout << "输入 0  为退出程序" << endl;

        int inputNumber;
        std::cin >> inputNumber;
        
        switch (inputNumber)
        {
        case 1:
            {
            std::cout << "请输入进货的重量:" << endl;
            double weight;
            std::cin >> weight;
            Buy(head, weight);
            }
            break;
        case 2:
            Sale(head);
            break;
        case 0: return;
        default: cout << "\nError! Press any key to select again." << endl;
        }
        std::cout << "仓库的总重量为:" << Goods::Get_total_weight() << endl;
    } while (1);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值