// Oldham, Jeffrey D. // 2000Feb07 // CS1321 // Declaration and Implementation of the Shopping Cart Class #include #include #include #include // has pair<>() #include // has accumulate() #include // has for_each() // Each item has a name and a price. typedef pair itemNP; // instead of typing pair<...> all the time // Print an item on a line. void printItem(const itemNP & itm) { cout << itm.first << " $" << itm.second << endl; return; } // Add an item's price to the total so far. double addPrice(const double total, itemNP itm) { return total + itm.second; } class shoppingCart { public: // Anyone can access public functions and data. // Constructor: invoked when creating a shopping cart. /* 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) { return accumulate(items.begin(), items.end(), 0.0, addPrice); } // 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; } // Private functions and members only accessible inside the class definition. // Useful as "helpers." private: string name; // name of customer vector items; };