我被困在为计算机科学课编写的C++程序上

I'm stuck on a C++ program that i'm writing for my computer science class

本文关键字:C++ 程序上 科学课 计算机      更新时间:2023-10-16

当我尝试运行此程序时,它将为我的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 

我的怀疑是,getTotalCost添加0值:

cartItems[i].getQuantity() * cartItems[i].getPrice();

如果两个因素之一为零,则整个总和保持0。