gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
can give me a c++ code.
- User
can give me a c++ code.
- Assistant
can give me a c++ code.
Sure! I can provide you with a simple example of C++ code. Below is a program that demonstrates a basic implementation of a class in C++ to manage a simple bank account:
#include <iostream>
#include <string>
class BankAccount {
private:
std::string accountHolder;
double balance;
public:
// Constructor to initialize the account
BankAccount(std::string name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
// Function to deposit money
void deposit(double amount) {
if (amount > 0) {
balance += amount;
std::cout << "Deposited: $" << amount << "\n";
} else {
std::cout << "Deposit amount must be positive!\n";
}
}
// Function to withdraw money
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
std::cout << "Withdrew: $" << amount << "\n";
} else {
std::cout << "Withdrawal amount must be positive and less than or equal to balance!\n";
}
}
// Function to display account details
void displayAccountInfo() const {
std::cout << "Account Holder: " << accountHolder << "\n";
std::cout << "Current Balance: $" << balance << "\n";
}
};
int main() {
// Create a new bank account for John Doe with an initial balance of $1000
BankAccount account("John Doe", 1000.0);
// Display account information
account.displayAccountInfo();
// Perform some transactions
account.deposit(250.0);
account.withdraw(100.0);
account.withdraw(1200.0); // Should show an error message
// Display updated account information
account.displayAccountInfo();
return 0;
}
BankAccount class has private members for the account holder's name and the account balance.BankAccount object is created.deposit and withdraw functions allow adding to and subtracting from the balance while checking for valid amounts.displayAccountInfo function prints the current account details.main function, an instance of BankAccount is created, and various operations are performed on it.You can compile and run this program using a C++ compiler. For example, if you are using g++, you can do so via the command line:
g++ bank_account.cpp -o bank_account
./bank_account
Just replace bank_account.cpp with the name of your source file.