Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Cree una clase llamada "Producto" con atributos como nombre, precio y cantidad en stock.
2. Implemente métodos para la compra y venta de productos, que actualizarán el stock según la cantidad comprada o vendida.
3. Agregue un método para mostrar los detalles del producto, incluyendo su nombre, precio y cantidad en stock.
4. Implemente una función principal que permita crear un producto, simular compras y ventas, y mostrar información actualizada del producto.
Desarrolle un sistema de inventario con clases para productos y operaciones de compra y venta.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the standard input/output library
#include <string> // Include the string library
using namespace std;
// Define the 'Product' class to represent a product in the inventory
class Product {
private:
string name; // Product name
double price; // Product price
int quantity; // Quantity in stock
public:
// Constructor to initialize the product with its details
Product(string n, double p, int q) {
name = n;
price = p;
quantity = q;
}
// Method to buy a certain quantity of the product (add to stock)
void buy(int amount) {
quantity += amount; // Increase the quantity by the purchase amount
cout << amount << " units of " << name << " purchased." << endl;
}
// Method to sell a certain quantity of the product (decrease stock)
void sell(int amount) {
if (quantity >= amount) {
quantity -= amount; // Decrease the quantity by the sale amount
cout << amount << " units of " << name << " sold." << endl;
} else {
cout << "Not enough stock to sell " << amount << " units." << endl;
}
}
// Method to display the product details (name, price, quantity)
void displayInfo() {
cout << "Product: " << name << endl;
cout << "Price: $" << price << endl;
cout << "Quantity in stock: " << quantity << endl;
}
};
int main() {
// Create a product called 'Laptop' with a price of $1000 and 10 units in stock
Product laptop("Laptop", 1000.0, 10);
// Display the initial product information
laptop.displayInfo();
// Simulate a purchase of 5 units
laptop.buy(5);
// Simulate a sale of 8 units
laptop.sell(8);
// Display the updated product information
laptop.displayInfo();
// Attempt to sell more units than available
laptop.sell(10);
return 0; // Return 0 to indicate successful execution
}
Salida
Product: Laptop
Price: $1000
Quantity in stock: 10
5 units of Laptop purchased.
8 units of Laptop sold.
Product: Laptop
Price: $1000
Quantity in stock: 7
Not enough stock to sell 10 units.
Comparte este ejercicio C++