这是我的主要内容:
int main() {
Inventory Master;
bool flag;
Customer Bob("Bob", "CreditCard.txt");
Customer Joe("Joe", "CreditCard.txt" );
Master.firststock( "inventory.txt" );
vector<Food> temp = Master._Inv;
cout <<"Hi, What would you like to buy today?" << endl;
for(unsigned int i=0; i<temp.size(); i++ ) {
cout << temp[i].name << " " << temp[i].quant << " " << temp[i].price << endl;
}
cout <<"n";
Food Apple("Apples", .99, 10);
Food Orange("Oranges", .99, 10);
Food Chip("Chips", 3.00, 10);
cout <<"nHi Bob" << endl;
flag = Bob.addCart(Apple, 7, &Master);
cout <<"Bob's total purchases are Currently: n";
Bob.report();
flag = Bob.addCart(Orange, 2, &Master);
flag = Bob.addCart(Chip, 2, &Master);
Bob.report();
flag = Bob.removeCart();
Bob.report();
cout <<"Bob, ";
flag = Bob.checkout(&Master);
以下是我实现的从矢量中删除食物的步骤_Cart:
bool Customer::removeCart() {
bool flag;
int q = 0;
unsigned int i=0;
string remove;
cout << "nWhat would you like to remove and how much would you like to remove?" << endl;
cin >> remove >> q;
for (i =0; i < _Cart.size(); i++) {
if(remove == _Cart[i].name) {
if (q >= 0) {
_Cart[i].quant -= q;
//inv->_Inv[i].quant += q;
cout <<"nYou removed " << q << " " << remove <<" In your cartn" << endl;
return true;
}
if (q < 0) {
cout << "Invalid number of " << remove << " being removed.n" << endl;
return true;
}
}
else {
try {
throw remove;
}
catch (string param) {
cout << "n" << remove << " doesn't exist in your cartn" << endl;
}
return true;
}
}
我的标题包含函数removeCart:
class Customer {
public:
Customer(string n, string fileName);
~Customer() { _Cart.clear(); };
bool addCart(Food f, int q, Inventory* inv);
bool removeCart();
void report();
bool checkout(Inventory* inv);
protected:
string remove;
string name;
int q;
int card;
double balance;
CreditCard _CC(int card,double balance);
vector<Food> _Cart;
};
现在,出于某种原因,当我调用removeCart时,输入"Apples"有效,但我注意到我制作了一个名为Apple的食物对象,所以不确定为什么输入"Apple"而不是"Apple"有效。同样,当我尝试"橙色"或"芯片"时,会显示异常,但正如你所看到的,我将芯片和橙色添加到了Bob的购物车中。我很感激你的帮助。
您正在创建一个名为Apple的对象,该对象包含一个std::string类型的成员,该成员包含字符"Apples"。只有你的编译器知道你调用了一个对象Apple,但你的程序会将字符串"Apples"与你的输入进行比较。Orange和Chip也是如此。
您已经在代码中的某个位置声明了一个名为Apple
的对象。
然后,实例化了Apple
类的实例,并将Apple::name
成员设置为字符串'Apples'
。
您不是在将输入与类名进行比较,而是在将输入与Apple
类的成员数据进行比较。