Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Defina una clase llamada "CuentaBancaria" con un atributo privado: saldo (doble).
2. Añada un constructor para inicializar el saldo a cero.
3. Implemente un método para depositar dinero en la cuenta.
4. Implemente un método para retirar dinero de la cuenta, garantizando que el saldo no sea negativo.
5. Implemente un método para consultar y mostrar el saldo actual.
6. En la función principal, cree un objeto de la clase CuentaBancaria, deposite dinero, retire dinero y consulte el saldo.
Desarrolle una clase CuentaBancaria con métodos para depositar, retirar y consultar el saldo.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the standard input/output library
using namespace std;
// Define the 'BankAccount' class
class BankAccount {
private:
double balance; // Private attribute for the account balance
public:
// Constructor to initialize the balance to zero
BankAccount() {
balance = 0.0; // Set the balance to 0 initially
}
// Method to deposit money into the account
void deposit(double amount) {
if (amount > 0) { // Ensure the deposit amount is positive
balance += amount; // Add the amount to the balance
cout << "$" << amount << " deposited successfully." << endl;
} else {
cout << "Deposit amount must be positive!" << endl;
}
}
// Method to withdraw money from the account
void withdraw(double amount) {
if (amount > 0 && amount <= balance) { // Ensure withdrawal is valid
balance -= amount; // Subtract the amount from the balance
cout << "$" << amount << " withdrawn successfully." << endl;
} else if (amount > balance) {
cout << "Insufficient balance!" << endl; // Handle insufficient balance
} else {
cout << "Withdrawal amount must be positive!" << endl; // Handle invalid withdrawal
}
}
// Method to check and display the current balance
void checkBalance() {
cout << "Current balance: $" << balance << endl; // Display the balance
}
};
int main() {
// Create a 'BankAccount' object
BankAccount myAccount;
// Deposit money into the account
myAccount.deposit(500.0);
// Withdraw money from the account
myAccount.withdraw(200.0);
// Check and display the current balance
myAccount.checkBalance();
// Try an invalid withdrawal (insufficient balance)
myAccount.withdraw(400.0);
// Check balance again
myAccount.checkBalance();
return 0; // Return 0 to indicate successful execution
}
Salida
$500 deposited successfully.
$200 withdrawn successfully.
Current balance: $300
Insufficient balance!
Current balance: $300
Comparte este ejercicio C++