The C++ Account class creates a class named Account.

This class should include a data member of type int representing the account balance.

Notice:

This class must provide a constructor: it receives the initial balance and initializes the data members with it. This number should confirm the validity of the initial balance, ensuring that it is greater than or equal to zero. Otherwise, the balance should be set to 0, and the constructor must display an error message stating that the initial balance is invalid.

This class also provides 3 member functions, the member function credit adds an amount to the current balance. debit will withdraw money from this Account, and guarantee that the withdrawn amount will not exceed the balance of this Account. If not, the balance is unchanged and the function prints a message stating "Debit amount exceeded account balance." The member function getBalance returns the current balance. Write a test program that creates two Account objects and tests the member functions of the Account class.

The running code is as follows:

#include<iostream>
using namespace std;

class Account
{
	public:
		Account( int initial )//这是构造函数 
		{
			if(initial>=0)//保证大于等于0
			{
				number = initial;
			}
			else
			{
				number = 0;
				cout << "error" << endl;
			}	
			
		}
		
		void Credit(int addition)// Credit函数
		{
			number += addition;
		}
		
		void debit(int take)//debit函数
		{
			if(take > number)
			{
				cout << "Debit amount exceeded account balance." << endl;
			}
			else
			{
				number -= take; 
			}
		}
		
		void getBalance()//getBalance函数
		{
			cout << "当前余额为:" << number << endl; 
		}
		
	private:	
		int number;	//账户余额
};

//测试程序
int main()
{
	Account account1(1000),account2(5000);//创建两个Account对象
	//分别测试两个对象的成员函数

	account1.Credit(1000);
	account1.debit(2000);
	account1.getBalance();
	  
	account2.Credit(1800);
	account2.debit(2800);
	account2.getBalance();
	     
	return 0;
}

If there are any deficiencies, welcome to give me valuable suggestions and opinions in the comment area, thank you!

Guess you like

Origin blog.csdn.net/weixin_74287172/article/details/130309362