A shop uses a class to store data about items for sale in the shop. This data includes: name of item (for example: “bread”) price of item (for example: $3.19) number of items in stock (for example: 120) Design the class and write suitable methods to load the data and display the data. There are many items in the shop so you will need an array of objects. Write a method that enters the name of an item and how many items have just been sold. The method must also update the number of items in the object. for example: Enter item that was just sold: bread How many items were sold: 2 Number of bread items in the shop is now 118 use c++ Write a main program to test your class.
时间: 2023-12-31 19:04:07 浏览: 68
Here is a possible implementation of the class and main program in C++:
```c++
#include <iostream>
#include <string>
using namespace std;
class ShopItem {
public:
string name;
double price;
int stock;
void load(string n, double p, int s) {
name = n;
price = p;
stock = s;
}
void display() {
cout << name << " - " << price << " - " << stock << endl;
}
void sell(int quantity) {
if (quantity <= stock) {
stock -= quantity;
cout << "Number of " << name << " items in the shop is now " << stock << endl;
} else {
cout << "Not enough " << name << " items in stock." << endl;
}
}
};
int main() {
const int NUM_ITEMS = 3;
ShopItem items[NUM_ITEMS];
// Load data
items[0].load("Bread", 3.19, 120);
items[1].load("Milk", 2.49, 80);
items[2].load("Eggs", 1.99, 200);
// Display data
for (int i = 0; i < NUM_ITEMS; i++) {
items[i].display();
}
// Sell items
string item_name;
int quantity;
cout << "Enter item that was just sold: ";
getline(cin, item_name);
cout << "How many items were sold: ";
cin >> quantity;
for (int i = 0; i < NUM_ITEMS; i++) {
if (items[i].name == item_name) {
items[i].sell(quantity);
break;
}
}
return 0;
}
```
The `ShopItem` class has three variables: `name` (string), `price` (double), and `stock` (integer), as well as three methods: `load`, `display`, and `sell`. The `load` method sets the values of the variables for each object, the `display` method prints out the values, and the `sell` method updates the `stock` variable if there are enough items in stock.
In the `main` function, an array of `ShopItem` objects is created with a size of `NUM_ITEMS`. The data is loaded into each object using the `load` method. The data is displayed using the `display` method. The user is prompted to enter an item name and a quantity of items sold, and the `sell` method is called on the corresponding object to update the stock.
阅读全文