C++自动售货机程序问题:如何在main()获取输入并调用Base子类选项
解决自动售货机的用户输入与商品展示问题
Hey there! Let's break down how to tackle this vending machine problem step by step. I'll walk you through designing the class structure, fetching product options from your subclasses, and handling user input in main().
1. 先设计清晰的基类与子类结构
首先,你的Base类应该定义通用的商品接口(比如获取名称、价格的方法),子类(比如Snack、Drink)去实现这些接口。这样我们就能利用多态来统一处理所有商品:
#include <iostream> #include <vector> #include <string> // 基类 Base class Base { public: // 纯虚函数,子类必须实现 virtual std::string getName() const = 0; virtual double getPrice() const = 0; virtual ~Base() = default; // 虚析构函数,避免内存泄漏 }; // 子类:零食类 class Snack : public Base { private: std::string name; double price; public: Snack(std::string n, double p) : name(n), price(p) {} std::string getName() const override { return name; } double getPrice() const override { return price; } }; // 子类:饮料类 class Drink : public Base { private: std::string name; double price; public: Drink(std::string n, double p) : name(n), price(p) {} std::string getName() const override { return name; } double getPrice() const override { return price; } };
2. 在main()中展示商品选项
我们可以用一个vector存储基类指针(利用多态),把所有商品实例放进去,然后遍历这个容器来打印所有商品的名称和价格:
int main() { // 存储所有商品 std::vector<Base*> products; products.push_back(new Snack("Chips", 1.5)); products.push_back(new Snack("Chocolate Bar", 2.0)); products.push_back(new Drink("Soda", 1.8)); products.push_back(new Drink("Water", 1.0)); // 打印商品菜单 std::cout << "=== Vending Machine Menu ===" << std::endl; for (int i = 0; i < products.size(); ++i) { std::cout << i + 1 << ". " << products[i]->getName() << " - $" << products[i]->getPrice() << std::endl; }
3. 获取并处理用户输入
接下来用cin获取用户的选择,然后做合法性检查(比如输入是否在有效范围内),最后处理用户的请求:
// 获取用户输入 int choice; std::cout << "\nEnter the number of your choice: "; while (!(std::cin >> choice) || choice < 1 || choice > products.size()) { // 处理非法输入 std::cin.clear(); // 清除错误状态 std::cin.ignore(1000, '\n'); // 忽略缓冲区的无效输入 std::cout << "Invalid choice! Please enter a number between 1 and " << products.size() << ": "; } // 处理用户选择 Base* selectedProduct = products[choice - 1]; std::cout << "\nYou selected: " << selectedProduct->getName() << " ($" << selectedProduct->getPrice() << ")" << std::endl; // 这里可以添加后续逻辑,比如收款、出货等 // 清理内存 for (auto product : products) { delete product; } products.clear(); return 0; }
关键要点说明
- 多态的使用:通过基类指针调用子类的
getName()和getPrice(),这样不管你新增多少种商品子类,都不用修改展示和输入处理的逻辑。 - 输入合法性检查:用循环确保用户输入的是有效数字且在菜单范围内,避免程序崩溃。
- 内存管理:记得手动删除
new出来的对象,或者改用智能指针(比如std::unique_ptr<Base>)来自动管理内存,更安全。
内容的提问来源于stack exchange,提问作者user7716102
相关产品推荐
相关产品推荐

