// Oldham, Jeffrey D. // 2000Feb07 // CS1321 // Definition of the Shopping Cart Class #include #include #include #include // has pair<>() #include // has for_each() #include // has accumulate() #include // has floor() and fabs() class shoppingCart { public: // Anyone can access public functions and data. // Each item has a name and a price. typedef pair itemNP; // instead of typing pair<...> all the time // Constructors: invoked when creating a shopping cart. // Two different constructors permit creating the shopping cart without // and with a name. /* no return type permitted */ shoppingCart(void) { name = "Anonymous"; return; } /* no return type permitted */ shoppingCart(const string & nm) { name = nm; return; } // Add an item to the cart. void insert(const string & itemName, const double price) { items.push_back(make_pair(itemName, price)); return; } // Return the cost of items already in the cart. double totalSoFar(void) const { return accumulate(items.begin(), items.end(), 0.0, addPrice); } // Multiply all the prices by the given value. void operator*=(const double multiplier) { for (vector::iterator i = items.begin(); i != items.end(); ++i) (*i).second = rounder((*i).second * multiplier); return; } // Accept the credit card number and print a receipt. void checkout(const string & creditCard) { // Notify the customer of charge to credit card. cout << "Charging credit card " << creditCard << " $" << totalSoFar() << endl; // Print the receipt. cout << name << ", thank you for shopping at The Best.\n"; for_each(items.begin(), items.end(), printItem); cout << endl; cout << "Total: " << totalSoFar() << endl; // Remove the items from the cart. items.clear(); return; } friend ostream& operator<<(ostream& out, const shoppingCart & sc); // Private functions and members only accessible inside the class definition. // Useful as "helpers." private: string name; // name of customer vector items; // We need this unary function when printing the receipt. Without // static, the function conceptually has an implicit first parameter // of the current object. Using static, there is no implicit first // parameter. Also we cannot access any of the object's members, // e.g., insert(...) or items. static void printItem(const itemNP & itm) { cout << itm.first << " $" << itm.second << endl; return; } // Add an item's price to the total so far. static double addPrice(const double total, itemNP itm) { return total + itm.second; } // Round a price to two decimal points. static double rounder(const double d) { return (d >= 0.0 ? +1 : -1) * floor(fabs(d * 100) + 0.5) / 100; } }; ostream& operator<<(ostream& out, const shoppingCart & sc) { // Note use of shoppingCart::itemNP! for (vector::const_iterator i = sc.items.begin(); i != sc.items.end(); ++i) out << (*i).first << " $" << (*i).second << endl; return out; }