Bài tập C++ OOP: tạo lớp Account giống như theo yêu cầu | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Creat Account class in Account.cpp file with the following information:

Explanation:

  • Account class describes the information of bank accounts.
  • id, name and balance attributes are the ID account, name of the account and the availabe balance respectively.
  • Account(id: int, name: String) and Account(id: int, name: String, balance: int) are parameterized constructor used to declare the corresponding attributes.
  • getId(), setName(), getName(), getBalance() are the setters and getters.
  • deposit(amount: int) method is used to deposit an amount of money (balance += amount).
  • withdraw(amount: int) method is used to withdraw an amount of money (balance -= amount). If the balance of the account is not enough (balance < amount), do not withdraw money. The screen will display as below:
    That amount exceeds your current balance.​
  • display() method is used to display the account information on the screen. For example, if id = 1000, name = "Tuan", balance = 2490, when the display() method is called, it produces the following result:
    Id: 1000
    Name: Tuan
    Balance: 2490​

The below program is used to test Account class:

#include <iostream>
#include "Account.cpp"

using namespace std;

int main() {
	Account account1(1000, "Tuan", 2000);
	account1.display();
	account1.withdraw(2100);
	account1.deposit(600);
	cout << "Balance: " << account1.getBalance() << endl;
	account1.withdraw(2100);
	cout << "Balance: " << account1.getBalance() << endl;
	return 0;
}

When the above code is compiled and executed, it produces the following result:

Id: 1000
Name: Tuan
Balance: 2000
That amount exceeds your current balance.
Balance: 2600
Balance: 500

Instruction

You need to create Account class as below:

#include<iostream>
using namespace std;
class Account {
private:
	int id;
	string name;
	int balance = 0;

public:
	Account(int id, string name) {
		this->id = id;
		this->name = name;
	}

	Account(int id, string name, int balance) {
		this->id = id;
		this->name = name;
		this->balance = balance;
	}

	int getId() {
		return id;
	}

	string getName() {
		return name;
	}

	void setName(string name) {
		this->name = name;
	}

	int getBalance() {
		return balance;
	}
	void deposit(int amount) {
		balance += amount;
	}
	void withdraw(int amount) {
		if (balance >= amount) {
			balance -= amount;
		} else {
			cout << "That amount exceeds your current balance." << endl;
		}
	}
	void display() {
		cout << "Id: " << id << endl;
		cout << "Name: " << name << endl;
		cout << "Balance: " << balance << endl;
	}
};