【发布时间】:2018-04-24 05:43:17
【问题描述】:
当我尝试运行这个程序时,它为我的 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
【问题讨论】:
-
附带说明,在头文件中使用
using namespace std通常不是一个好习惯(例如,在您的customerName类成员的情况下:std: :string customerName) -
我个人认为这不是一个好主意,我不喜欢使用它,但我的教授让我们这样做。
-
我看不出这段代码有什么问题。也许忘记添加一个项目?将数量或价格设置为零?也许您可以在
changeQuantity等中添加一个检查。 -
我可以看到四个可能的原因:1)购物车是空的; 2)您的物品数量为零; 3) 您的商品价格为零; 4) 某些商品的价格或数量为负,它们加起来为零。我怀疑您要么 a) 将商品添加到与您正在检查的购物车不同的购物车中,要么 b) 将默认构造的商品添加到购物车中。