21xrx.com
2024-09-20 00:17:20 Friday
登录
文章检索 我的文章 写文章
C++自动售货机类
2023-07-02 14:30:48 深夜i     --     --
C++ 自动售货机 程序设计 面向对象

自动售货机是一种自动化的设备,便于人们在不同场合购买商品。在现代社会,自动售货机已经普及到各个领域,如酒店、机场、火车站、商场等。为了更好地管理自动售货机,我们可以通过用 C++ 编写自动售货机类,使其功能更加完善。

在自动售货机类中,我们可以定义一些属性,例如:存储商品的容量、商品的名字、价格、商品的数量等。同时,我们可以设置一些方法来管理这些属性,如购买商品、查看商品信息、添加商品、删除商品等。以下是一个示例代码:


#include <iostream>

#include <string>

using namespace std;

class VendingMachine{

public:

  VendingMachine(); //构造函数初始化

  void buy(string name); //购买商品

  void add(string name, int count, float price); //添加商品

  void del(string name); //删除商品

  void show(string name); // 查看商品信息

private:

  int Capacity; //存储商品的容量

  string Name[100]; //商品名称

  int Count[100]; //商品数量

  float Price[100]; //价格

};

VendingMachine::VendingMachine(){

  Capacity = 100;

  for(int i=0;i<Capacity;i++){

    Name[i] = "0";

    Count[i] = 0;

    Price[i] = 0;

  }

}

void VendingMachine::buy(string name){

  int flag = 0;

  for(int i=0;i<Capacity;i++){

    if(Name[i] == name){

      if(Count[i] <= 0) //商品数量不足

        flag = -1;

        break;

      

      else{

        flag = 1;

        cout << "Buy Successfully!" << endl;

        Count[i] -= 1;

        break;

      }

    }

  }

  if(flag == 0) We Don't Sell This Product!" << endl;

  

  else if (flag == -1)

    cout << "Sorry

}

void VendingMachine::add(string name, int count, float price){

  for(int i=0;i<Capacity;i++){

    if(Name[i] == "0"){

      Name[i] = name;

      Count[i] = count;

      Price[i] = price;

      break;

    }

  }

  cout << "Add Successfully!" << endl;

}

void VendingMachine::del(string name){

  for(int i=0;i<Capacity;i++){

    if(Name[i] == name){

      Name[i] = "0";

      Count[i] = 0;

      Price[i] = 0;

      break;

    }

  }

  cout << "Delete Successfully!" << endl;

}

void VendingMachine::show(string name){

  int index = -1;

  for(int i=0;i<Capacity;i++){

    if(Name[i]==name)

      index = i;

      break;

    

  }

  if(index == -1)

    cout << "The Product Is Not Found!" << endl;

  

  else{

    cout << "Name: " << Name[index] << endl;

    cout << "Count: " << Count[index] << endl;

    cout << "Price: " << Price[index] << endl;

  }

}

在上述代码中,我们定义了一个自动售货机类 VendingMachine,包含了一些功能方法来实现购买、添加、删除和查看商品信息的操作。同时,我们也定义了一些属性来表示商品的存储容量、商品的名称、价格和数量。

在 VendingMachine 类的构造函数中,我们初始化了所有的属性,将它们都设置为初始状态。然后,我们分别定义了购买、添加、删除和查看商品信息的方法,这些方法通过判断商品的名称来实现相应的操作,并输出相应的结果。

总结:

通过使用 C++ 编写自动售货机类,我们可以更好地管理自动售货机,使其更加智能化。我们可以通过 C++ 的面向对象编程来实现各种不同的功能,例如购买、添加、删除和查看商品信息等。以上代码提供了一些示例方法,可以根据实际情况进行修改和完善。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复