【发布时间】:2018-02-07 17:11:14
【问题描述】:
我目前正在研究自动售货机程序。但是,我无法弄清楚如何要求用户输入并打印出选项和价格。这是我的代码的一部分,我的问题是:如何在 main() 中向用户询问输入并从 Base 子类中获取选项。
提前谢谢你。
class Product
{
protected:
string product_description;
int itemCost = 0;
public:
virtual void consume(void)
{
}
virtual int cost(void) { return this->itemCost; }
virtual string description(void) { return product_description; }
virtual Product* ReturnHighestCostItem(void)
{
return this;
}
virtual void RemoveHighestCostItem(void)
{
return;
}
};
class Base : public Product
{
public:
Base(int option)
{
if (option == 1)
{
this->product_description = "Plain";
this->itemCost = 100;
}
else if (option == 2)
{
this->product_description = "Spicy";
this->itemCost = 150;
}
else if (option == 4)
{
this->product_description = "Chocolate";
this->itemCost = 200;
}
else if (option == 8)
{
this->product_description = "Coconut";
this->itemCost = 200;
}
else if (option == 16)
{
this->product_description = "Fruity";
this->itemCost = 200;
}
}
};
int main()
{
Product obj;
cout << "The Available descriptions are:" << obj.description()<< endl;
return 0;
}
【问题讨论】:
-
你的 main() 在哪里?你也听说过 std::cin 和 std::cout 吗?
-
考虑使用
switch/case而不是if/else if。 -
使用
switch,而不是if else if。 -
@user7716102 使用
std::cin继续操作有什么问题?
标签: c++