【发布时间】:2016-07-06 13:29:20
【问题描述】:
您好,我在创建 GroceryItem 类和使用函数接受和设置用户输入时遇到了一些麻烦。
目前,当我运行 dataEntry 函数时,编译器会在接受来自第一个函数的输入之前转到下一个函数。
我创建了一个测试牛奶对象来测试我的代码,但它不允许我在进入下一个输入提示之前输入数据。
一旦我能找出类函数,我还将创建一个对象数组并为其输入值。
任何关于如何修复此类和函数的建议将不胜感激!
#include <iostream>
using namespace std;
class GroceryItem{
private: int stockNumber;
double price = 0.0;
int quantity;
double totalValue;
double setPrice();
int setStockNum();
int setQuantity();
void setTotalValue();
public:
void dataEntry();
void displayValues();
};
int GroceryItem::setStockNum(){
int stock = 0;
cout << "Enter the stock number for the grocery item: ";
do {
cout << "Stock Number(1000-9999): ";
cin >> stock;
} while (!(stock >= 1000 && stock <= 9999));
stockNumber = stock;
return stockNumber;
}
double GroceryItem::setPrice(){
double x = 0.0;
cout << "Enter the price of the item: ";
while (!(x > 0)) {
cout << "Please enter a positive number for price!";
cin >> x;
}
price = x;
return price;
}
int GroceryItem::setQuantity(){
int x = 0;
cout << "Enter the quantity in stock: ";
while (!(x > 0)){
cout << "Please enter a positive number for quantity!";
cin >> x;
}
quantity = x;
return quantity;
}
void GroceryItem::setTotalValue(){
totalValue = (quantity * price);
}
void GroceryItem::dataEntry(){
setStockNum();
system("pause");
setPrice();
system("pause");
setQuantity();
system("pause");
setTotalValue();
}
void GroceryItem::displayValues(){
cout << "Stock number: " << stockNumber;
cout << "\nItem price: " << price;
cout << "\nQuantity on hand: " << quantity;
cout << "\nTotal value of item: " << totalValue;
}
int main(){
GroceryItem Milk;
Milk.dataEntry();
Milk.displayValues();
system("pause");
return 0;
}
【问题讨论】:
-
你这是什么意思?这不是有效的代码行,所以不确定您的意思
-
您应该使用构造函数初始化
price成员。 -
看起来很适合使用 调试器。
-
编写代码时,先从简单但完美运行的东西开始,然后一点一点地增加复杂性,每一步都进行测试; 永远不要添加不起作用的代码。
标签: c++ function class parameter-passing