这个类应该包括一个类型为int的数据成员,表示账户余额。
注意:
这个类必须提供一个构造函数:它接收初始余额并用它初始化数据成员。这个的造丽数应当确认初始余额的有效性,保证它大于或等于0。否则,余额应当设置为0,并且构造数必须显示一条错误信息,指出初始余额是无效的。
该类还要提供3个成员函数,成员函数credit将一笔金额加到当前余额中。debit将从这个Account中取钱,并保证取出金额不超过此Account的余额。如果不是这样,余额不变,函数打印一条信息,指出“Debit amount exceeded account balance.”成员函数 getBalance 将返回当前余额。编写一个测试程序,它创建两个Account对象,并测试Account类的成员函数。
运行代码如下:
#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;
}
如有不足,欢迎在评论区给我宝贵的建议和意见,谢谢!