当我尝试运行此程序时,它为我的getTotalCost()
函数输出0,我无法找出原因。
这是两个类文件:
ShoppingCart.cpp
#include "ShoppingCart.h"
#include <iostream>
#include <string>
using namespace std;
ShoppingCart::ShoppingCart()
{
customerName = "None";
}
ShoppingCart::ShoppingCart(string name)
{
customerName = name;
}
string ShoppingCart::getCustomerName() const
{
return customerName;
}
void ShoppingCart::addItem(ItemToPurchase item)
{
cartItems.push_back(item);
}
void ShoppingCart::removeItem(string name)
{
for (int i = 0; i < cartItems.size(); i++)
{
if (cartItems.at(i).getName() == name)
{
cartItems.erase(cartItems.begin() + i);
}
else
{
cout << "Item not found in cart. Nothing removed." << endl;
}
}
}
void ShoppingCart::changeQuantity(string name, int quantity)
{
for (int i = 0; i < cartItems.size(); i++)
{
if (cartItems.at(i).getName() == name)
{
cartItems[i].setQuantity(quantity);
}
else
{
cout << "Item not found in cart. Nothing modified." << endl;
}
}
}
double ShoppingCart::getTotalCost()
{
double sum = 0.0;
for (int i = 0; i < cartItems.size(); i++)
{
sum += cartItems[i].getQuantity() * cartItems[i].getPrice();
}
return sum;
}
void ShoppingCart::printCart()
{
cout << customerName << "'s Shopping Cart" << endl;
for (int i = 0; i < cartItems.size(); i++)
{
cartItems.at(i).printItemCost();
}
cout << endl;
cout << "Total: $" << getTotalCost() << endl;
}
ShoppingCart.h
#ifndef ShoppingCart_hpp
#define ShoppingCart_hpp
#include <string>
#include <vector>
#include "ItemToPurchase.h"
using namespace std;
class ShoppingCart
{
private:
string customerName;
vector<ItemToPurchase> cartItems;
public:
ShoppingCart();
ShoppingCart(string name);
string getCustomerName() const;
void addItem(ItemToPurchase);
void removeItem(string);
void changeQuantity(string, int);
double getTotalCost();
void printCart();
};
#endif
答案 0 :(得分:2)
我的怀疑是,getTotalCost添加了0个值:
cartItems[i].getQuantity() * cartItems[i].getPrice();
如果两个因子中的一个为零,则总和保持为0。