从银行管理系统看C++与Java的不同

老师布置了实验的任务–将C++代码写的银行管理系统改为Java版本的。在这个过程之中,产生了一些心得与体会:
1.最大的特点就是语法的不同,Java中有很多语法和C++不一样,需要细心的根据语境修改,又比如函数的调用,C++中直接使用floor()函数,使用#include头文件,而Java中使用Math.floor();语句。
又比如建立对象的方式不同,Java中是SavingsAccount sa0=new SavingsAccount(1, 21325302, 0.015);而C++中是SavingsAccount sa0(1, 21325302, 0.015);即可。诸如此类的语法差异还有许多。
2.继承方式不同:Java中是单继承,而C++是多继承,这也就导致了纯虚函数与抽象函数的区别。
3.在这个过程之中遇到的最大的困难就是C++中"运算符重载"在Java中的实现,由于Java中没有“运算符重载”,只能通过相关函数来实现,有时候不知道代码中的哪些位置使用了·运算符重载,所以识别起来十分困难。

//4_9.cpp
#include <iostream>
#include <cmath>
using namespace std;

class SavingsAccount { //储蓄账户类
private:
	int id;				//账号
	double balance;		//余额
	double rate;		//存款的年利率
	int lastDate;		//上次变更余额的时期
	double accumulation;	//余额按日累加之和

	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(int date, double amount);
	//获得到指定日期为止的存款金额按日累积值
	double accumulate(int date) const {
		return accumulation + balance * (date - lastDate);
	}
public:
	//构造函数
	SavingsAccount(int date, int id, double rate);
	int getId() { return id; }
	double getBalance() { return balance; }
	double getRate() { return rate; }

	//存入现金
	void deposit(int date, double amount);
	//取出现金
	void withdraw(int date, double amount);
	//结算利息,每年1月1日调用一次该函数
	void settle(int date);
	//显示账户信息
	void show();
};

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(int date, int id, double rate)
	: id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
	cout << date << "\t#" << id << " is created" << endl;
}

void SavingsAccount::record(int date, double amount) {
	accumulation = accumulate(date);
	lastDate = date;
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
}

void SavingsAccount::deposit(int date, double amount) {
	record(date, amount);
}

void SavingsAccount::withdraw(int date, double amount) {
	if (amount > getBalance())
		cout << "Error: not enough money" << endl;
	else
		record(date, -amount);
}

void SavingsAccount::settle(int date) {
	double interest = accumulate(date) * rate / 365;	//计算年息
	if (interest != 0)
		record(date, interest);
	accumulation = 0;
}

void SavingsAccount::show() {
	cout << "#" << id << "\tBalance: " << balance;
}

int main() {
	//建立几个账户
	SavingsAccount sa0(1, 21325302, 0.015);
	SavingsAccount sa1(1, 58320212, 0.015);

	//几笔账目
	sa0.deposit(5, 5000);
	sa1.deposit(25, 10000);
	sa0.deposit(45, 5500);
	sa1.withdraw(60, 4000);

	//开户后第90天到了银行的计息日,结算所有账户的年息
	sa0.settle(90);
	sa1.settle(90);

	//输出各个账户信息
	sa0.show();	cout << endl;
	sa1.show();	cout << endl;
	return 0;
}

package SavingsAccount4_9;

public class SavingsAccount {
	
	private int id;				//账号
	private double balance;		//余额
	private double rate;		//存款的年利率
	private int lastDate;		//上次变更余额的时期
	private double accumulation;	//余额按日累加之和

		//记录一笔帐,date为日期,amount为金额,desc为说明
	private void record(int date, double amount) {
		accumulation = accumulate(date);
		lastDate = date;
		amount = Math.floor(amount * 100 + 0.5) / 100;	//保留小数点后两位,与C++调用floor不同,要加上Math
		balance += amount;
		//cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
	    System.out.println(date+"\t#"+id+"\t"+amount+"\t"+balance);
	}
	
		//获得到指定日期为止的存款金额按日累积值
	private final double accumulate(int date) {     //此处的const改为了final
			return accumulation + balance * (date - lastDate);
		}
	
	
	
		//构造函数
	SavingsAccount(int date, int id, double rate) {
		this.id=id;
		balance=0;
		this.rate=rate;
		lastDate=date;
		accumulation=0;
		System.out.println(date+"\t#"+id+"is created");
	}
	
	public int getId() { return id; }
	public double getBalance() { return balance; }
	public double getRate() { return rate; }

		//存入现金
	public void deposit(int date, double amount) {
		record(date, amount);
	}
		//取出现金
	public void withdraw(int date, double amount) {
		if (amount > getBalance())
			System.out.println("Error: not enough money");//输出方式有差异
		else
			record(date, -amount);
	}
		//结算利息,每年1月1日调用一次该函数
	public void settle(int date) {
		double interest = accumulate(date) * rate / 365;	//计算年息
		if (interest != 0)
			record(date, interest);
		accumulation = 0;
	}
		//显示账户信息
	public void show() {
        System.out.println("#"+id+"\tBalance:"+balance);
	}
	
	

	public static void main(String[] args) {
		//建立几个账户
		SavingsAccount sa0=new SavingsAccount(1, 21325302, 0.015);//amount cannot be resolved to a variable
		SavingsAccount sa1=new SavingsAccount(1, 58320212, 0.015);

		//几笔账目
		sa0.deposit(5, 5000);
		sa1.deposit(25, 10000);
		sa0.deposit(45, 5500);
		sa1.withdraw(60, 4000);

				//开户后第90天到了银行的计息日,结算所有账户的年息
				sa0.settle(90);
				sa1.settle(90);

				//输出各个账户信息
				sa0.show();	
				System.out.println("");
				sa1.show();	
				System.out.println("");
	}

}

以上两段代码的运行结果为

1       #21325302 is created
1       #58320212 is created
5       #21325302       5000    5000
25      #58320212       10000   10000
45      #21325302       5500    10500
60      #58320212       -4000   6000
90      #21325302       27.64   10527.6
90      #58320212       21.78   6021.78
#21325302       Balance: 10527.6
#58320212       Balance: 6021.78

在将例4_9的C++版本代码改为Java版本的代码之中需要注意的点如下:
1.Java中的方法不能写在类之外,而C++可以。
2.Java中表示常量使用关键字final,这和C++中使用const不同。
3.Java中的输出语法使用System.out.print();语句,而C++中主要使用的是cout语句。
4.建立一个SavingsAccount类的对象时,C++的语法是

SavingsAccount sa0(1, 21325302, 0.015);
SavingsAccount sa1(1, 58320212, 0.015);

Java不能通过这样来建立一个新对象,必须使用new语句。

SavingsAccount sa0=new SavingsAccount(1, 21325302, 0.015);
SavingsAccount sa1=new SavingsAccount(1, 58320212, 0.015);

5.main()语句不同,C++版本int main(){},Java版本public static void main(String[] args) {}
6.库函数使用方式不同。C++中的floor函数需要

#include <cmath>
//...
amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
//...

而Java

amount = Math.floor(amount * 100 + 0.5) / 100;
//保留小数点后两位,与C++调用floor不同,要加上Math
//  5_11.cpp
#include <iostream>
#include <cmath>
using namespace std;

class SavingsAccount { //储蓄账户类
private:
	int id;				//账号
	double balance;		//余额
	double rate;		//存款的年利率
	int lastDate;		//上次变更余额的时期
	double accumulation;	//余额按日累加之和
	static double total;	//所有账户的总金额

	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(int date, double amount);
	//获得到指定日期为止的存款金额按日累积值
	double accumulate(int date) const {
		return accumulation + balance * (date - lastDate);
	}
public:
	//构造函数
	SavingsAccount(int date, int id, double rate);
	int getId() const { return id; }
	double getBalance() const { return balance; }
	double getRate() const { return rate; }
	static double getTotal() { return total; }

	//存入现金
	void deposit(int date, double amount);
	//取出现金
	void withdraw(int date, double amount);
	//结算利息,每年1月1日调用一次该函数
	void settle(int date);
	//显示账户信息
	void show() const;
};

double SavingsAccount::total = 0;

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(int date, int id, double rate)
	: id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
	cout << date << "\t#" << id << " is created" << endl;
}

void SavingsAccount::record(int date, double amount) {
	accumulation = accumulate(date);
	lastDate = date;
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
}

void SavingsAccount::deposit(int date, double amount) {
	record(date, amount);
}

void SavingsAccount::withdraw(int date, double amount) {
	if (amount > getBalance())
		cout << "Error: not enough money" << endl;
	else
		record(date, -amount);
}

void SavingsAccount::settle(int date) {
	double interest = accumulate(date) * rate / 365;	//计算年息
	if (interest != 0)
		record(date, interest);
	accumulation = 0;
}

void SavingsAccount::show() const {
	cout << "#" << id << "\tBalance: " << balance;
}


int main() {
	//建立几个账户
	SavingsAccount sa0(1, 21325302, 0.015);
	SavingsAccount sa1(1, 58320212, 0.015);

	//几笔账目
	sa0.deposit(5, 5000);
	sa1.deposit(25, 10000);
	sa0.deposit(45, 5500);
	sa1.withdraw(60, 4000);

	//开户后第90天到了银行的计息日,结算所有账户的年息
	sa0.settle(90);
	sa1.settle(90);

	//输出各个账户信息
	sa0.show();	cout << endl;
	sa1.show();	cout << endl;
	cout << "Total: " << SavingsAccount::getTotal() << endl;
	return 0;
}

package SavingsAccount5_11;

public class SavingsAccount {
	//C++的全局变量total改为静态变量total,
	//total表示所有账户的总金额
	private static double total=0;      
	private int id;				//账号
	private double balance;		//余额
	private double rate;		//存款的年利率
	private int lastDate;		//上次变更余额的时期
	private double accumulation;	//余额按日累加之和

		//记录一笔帐,date为日期,amount为金额,desc为说明
	private void record(int date, double amount) {
		accumulation = accumulate(date);
		lastDate = date;
		amount = Math.floor(amount * 100 + 0.5) / 100;	//保留小数点后两位,与C++调用floor不同,要加上Math
		balance += amount;
		total += amount;
		//cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
	    System.out.println(date+"\t#"+id+"\t"+amount+"\t"+balance);
	}
	
		//获得到指定日期为止的存款金额按日累积值
	private final double accumulate(int date) {     //此处的const改为了final
			return accumulation + balance * (date - lastDate);
		}
	
	
	
		//构造函数
	SavingsAccount(int date, int id, double rate) {
		this.id=id;
		balance=0;
		this.rate=rate;
		lastDate=date;
		accumulation=0;
		System.out.println(date+"\t#"+id+"is created");
	}
	
	public final int getId() { return id; }
	public final double getBalance() { return balance; }
	public final double getRate() { return rate; }
	public static double getTotal() { return total; }

		//存入现金
	public void deposit(int date, double amount) {
		record(date, amount);
	}
		//取出现金
	public void withdraw(int date, double amount) {
		if (amount > getBalance())
			System.out.println("Error: not enough money");//输出方式有差异
		else
			record(date, -amount);
	}
		//结算利息,每年1月1日调用一次该函数
	public void settle(int date) {
		double interest = accumulate(date) * rate / 365;	//计算年息
		if (interest != 0)
			record(date, interest);
		accumulation = 0;
	}
		//显示账户信息
	public final void show() {
        System.out.println("#"+id+"\tBalance:"+balance);
	}
	
	

	public static void main(String[] args) {
		//建立几个账户
		SavingsAccount sa0=new SavingsAccount(1, 21325302, 0.015);//amount cannot be resolved to a variable
		SavingsAccount sa1=new SavingsAccount(1, 58320212, 0.015);

		//几笔账目
		sa0.deposit(5, 5000);
		sa1.deposit(25, 10000);
		sa0.deposit(45, 5500);
		sa1.withdraw(60, 4000);

				//开户后第90天到了银行的计息日,结算所有账户的年息
				sa0.settle(90);
				sa1.settle(90);

				//输出各个账户信息
				sa0.show();	
				System.out.println("");
				sa1.show();	
				System.out.println("");
				System.out.println("Total:"+SavingsAccount.getTotal());
	}

}

例5_11的输出结果为
`
1       #21325302 is created
1       #58320212 is created
5       #21325302       5000    5000
25      #58320212       10000   10000
45      #21325302       5500    10500
60      #58320212       -4000   6000
90      #21325302       27.64   10527.6
90      #58320212       21.78   6021.78
#21325302       Balance: 10527.6
#58320212       Balance: 6021.78
Total: 16549.4`

在将例5_11的C++版本代码改为Java版本的代码之中需要注意的点如下
1.c++中调用相关的类方法使用SavingsAccount::getTotal(),而Java中使用SavingsAccount.getTotal()

//6_25.cpp
#include <cmath>
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
class Date {	//日期类
private:
	int year;		//年
	int month;		//月
	int day;		//日
	int totalDays;	//该日期是从公元元年1月1日开始的第几天

public:
	Date(int year, int month, int day);	//用年、月、日构造日期
	int getYear() const { return year; }
	int getMonth() const { return month; }
	int getDay() const { return day; }
	int getMaxDay() const;		//获得当月有多少天
	bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	void show() const;			//输出当前日期
	//计算两个日期之间差多少天
	int distance(const Date& date) const {
		return totalDays - date.totalDays;
	}
};
namespace {	//namespace使下面的定义只在当前文件中有效
	//存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}

Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
	if (day <= 0 || day > getMaxDay()) {
		cout << "Invalid date: ";
		show();
		cout << endl;
		exit(1);
	}
	int years = year - 1;
	totalDays = years * 365 + years / 4 - years / 100 + years / 400
		+ DAYS_BEFORE_MONTH[month - 1] + day;
	if (isLeapYear() && month > 2) totalDays++;
}

int Date::getMaxDay() const {
	if (isLeapYear() && month == 2)
		return 29;
	else
		return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
	cout << getYear() << "-" << getMonth() << "-" << getDay();
}

class SavingsAccount { //储蓄账户类
private:
	std::string id;		//帐号
	double balance;		//余额
	double rate;		//存款的年利率
	Date lastDate;		//上次变更余额的时期
	double accumulation;	//余额按日累加之和
	static double total;	//所有账户的总金额

	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(const Date &date, double amount, const std::string &desc);
	//报告错误信息
	void error(const std::string &msg) const;
	//获得到指定日期为止的存款金额按日累积值
	double accumulate(const Date& date) const {
		return accumulation + balance * date.distance(lastDate);
	}
public:
	//构造函数
	SavingsAccount(const Date &date, const std::string &id, double rate);
	const std::string &getId() const { return id; }
	double getBalance() const { return balance; }
	double getRate() const { return rate; }
	static double getTotal() { return total; }

	//存入现金
	void deposit(const Date &date, double amount, const std::string &desc);
	//取出现金
	void withdraw(const Date &date, double amount, const std::string &desc);
	//结算利息,每年1月1日调用一次该函数
	void settle(const Date &date);
	//显示账户信息
	void show() const;
};
double SavingsAccount::total = 0;

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
	: id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
	date.show();
	cout << "\t#" << id << " created" << endl;
}

void SavingsAccount::record(const Date &date, double amount, const string &desc) {
	accumulation = accumulate(date);
	lastDate = date;
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	date.show();
	cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void SavingsAccount::error(const string &msg) const {
	cout << "Error(#" << id << "): " << msg << endl;
}

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount > getBalance())
		error("not enough money");
	else
		record(date, -amount, desc);
}

void SavingsAccount::settle(const Date &date) {
	double interest = accumulate(date) * rate	//计算年息
		/ date.distance(Date(date.getYear() - 1, 1, 1));
	if (interest != 0)
		record(date, interest, "interest");
	accumulation = 0;
}

void SavingsAccount::show() const {
	cout << id << "\tBalance: " << balance;
}

int main() {
	Date date(2008, 11, 1);	//起始日期
	//建立几个账户
	SavingsAccount accounts[] = {
		SavingsAccount(date, "S3755217", 0.015),
		SavingsAccount(date, "02342342", 0.015)
	};
	const int n = sizeof(accounts) / sizeof(SavingsAccount); //账户总数
	//11月份的几笔账目
	accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");
	accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
	//12月份的几笔账目
	accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
	accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");

	//结算所有账户并输出各个账户信息
	cout << endl;
	for (int i = 0; i < n; i++) {
		accounts[i].settle(Date(2009, 1, 1));
		accounts[i].show();
		cout << endl;
	}
	cout << "Total: " << SavingsAccount::getTotal() << endl;
	return 0;
}

package SavingsAccount6_25;

class Date {	//日期类

	private int year;		//年
	private int month;		//月
	private int day;		//日
	private int totalDays;	//该日期是从公元元年1月1日开始的第几天
	private final int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

	Date(int year, int month, int day) {
		//用年、月、日构造日期
		this.year=year;
		this.month=month;
		this.day=day;
		if (day <= 0 || day > getMaxDay()) {
			System.out.print("Invalid date: ");
			show();
			System.out.println("");
			//wait(1);
		}
		int years = year - 1;
		totalDays = years * 365 + years / 4 - years / 100 + years / 400
			+ DAYS_BEFORE_MONTH[month - 1] + day;
		if (isLeapYear() && month > 2) totalDays++;
	}
	
	public final int getYear() { return year; }
	public final int getMonth() { return month; }
	public final int getDay()  { return day; }
	public final int getMaxDay() {
		//获得当月有多少天
		if (isLeapYear() && month == 2)
			return 29;
		else
			return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
	}
	
	public final boolean isLeapYear() {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	
	public final void show() {
		//输出当前日期
		System.out.print(getYear()+"-"+getMonth()+"-"+getDay());
	}
	
	//计算两个日期之间差多少天
	public final int distance(final Date date) {
		return totalDays - date.totalDays;
	}

package SavingsAccount6_25;

public class SavingsAccount {
	//储蓄账户类

	private String id;		//帐号
	private double balance;		//余额
	private double rate;		//存款的年利率
	private Date lastDate;		//上次变更余额的时期
	private double accumulation;	//余额按日累加之和
	private static double total=0;	//所有账户的总金额

	//记录一笔帐,date为日期,amount为金额,desc为说明
	private void record(final Date date, double amount, final String desc) {
		accumulation = accumulate(date);
		lastDate = date;
		amount = Math.floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
		balance += amount;
		total += amount;
		date.show();
		System.out.println("\t#"+id+"\t"+amount+"\t"+balance+"\t"+desc);
	}
	
	//报告错误信息
	private final void error(final String msg) {
	    System.out.println("Error(#"+id+"): "+msg);
	}
	
	//获得到指定日期为止的存款金额按日累积值
	private final double accumulate(final Date date) {
		return accumulation + balance * date.distance(lastDate);
	}
	
	//构造函数
	SavingsAccount(final Date date, final String id, double rate){
		this.id=id;
		balance=0;
		this.rate=rate;
		lastDate=date;
		accumulation=0;
		date.show();
		System.out.println("\t#"+id+" created");
	}
	
	public final String getId() { return id; }
	public final double getBalance() { return balance; }
	public final double getRate() { return rate; }
	public static double getTotal() { return total; }

	//存入现金
	public void deposit(final Date date, double amount, final String desc) {
		record(date, amount, desc);
	}
	
	//取出现金
	public void withdraw(final Date date, double amount, final String desc) {
		if (amount > getBalance())
			error("not enough money");
		else
			record(date, -amount, desc);
	}
	
	//结算利息,每年1月1日调用一次该函数
	public void settle(final Date date) {
		double interest = accumulate(date) * rate / date.distance(new Date(date.getYear()-1, 1, 1));
		//此处要传对象,与C++不同,不可直接调用Date的构造函数,
		//即Date(date.getYear()-1, 1, 1)不可直接使用,要new一个对象
		//计算年息	
		if (interest != 0)
				record(date, interest," interest");
			accumulation = 0;
	}
	
	

	//显示账户信息
	public final void show() {
		System.out.println(id+"\tBalance: "+balance);
	}
	
	public static void main(String[] args) {
		Date date=new Date(2008, 11, 1);	//起始日期
		//建立几个账户
		SavingsAccount accounts[] = {
			new SavingsAccount(date, "S3755217", 0.015),
			new SavingsAccount(date, "02342342", 0.015)
		};
		final int n = accounts.length; //账户总数
		//11月份的几笔账目
		accounts[0].deposit(new Date(2008, 11, 5), 5000, "salary");
		accounts[1].deposit(new Date(2008, 11, 25), 10000, "sell stock 0323");
		//12月份的几笔账目
		accounts[0].deposit(new Date(2008, 12, 5), 5500, "salary");
		accounts[1].withdraw(new Date(2008, 12, 20), 4000, "buy a laptop");

		//结算所有账户并输出各个账户信息
	    System.out.println("");
		for (int i = 0; i < n; i++) {
			accounts[i].settle(new Date(2009, 1, 1));
			accounts[i].show();
		    System.out.println("");
		}
		System.out.println("Total: "+SavingsAccount.getTotal());
	}

运行结果

2008-11-1       #S3755217 created
2008-11-1       #02342342 created
2008-11-5       #S3755217       5000    5000    salary
2008-11-25      #02342342       10000   10000   sell stock 0323
2008-12-5       #S3755217       5500    10500   salary
2008-12-20      #02342342       -4000   6000    buy a laptop

2009-1-1        #S3755217       17.77   10517.8 interest
S3755217        Balance: 10517.8
2009-1-1        #02342342       13.2    6013.2  interest
02342342        Balance: 6013.2
Total: 16531

在将例6_25的C++版本代码改为Java版本的代码之中需要注意的点如下:
1.
namespace { //namespace使下面的定义只在当前文件中有效 //存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项 const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; }
相当于Date类之中的
private final int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
2.返回类型
c++中的

bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}

Java中的
public final boolean isLeapYear() { //判断当年是否为闰年 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; }为boolean,而不是bool,Java中的boolean只能为true或false,不能为数字。
3.exit(1);改为

System.exit(1);

4.std::string id; //帐号改为String id;
5.Java中对象之间传递的是引用,故不需要C++中的&来取地址。

//7_10
#include <iostream>
#include <cstdlib>
#include<cmath>
using namespace std;

class Date {	//日期类
private:
	int year;		//年
	int month;		//月
	int day;		//日
	int totalDays;	//该日期是从公元元年1月1日开始的第几天

public:
	Date(int year, int month, int day);	//用年、月、日构造日期
	int getYear() const { return year; }
	int getMonth() const { return month; }
	int getDay() const { return day; }
	int getMaxDay() const;		//获得当月有多少天
	bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	void show() const;			//输出当前日期
	//计算两个日期之间差多少天
	int distance(const Date& date) const {
		return totalDays - date.totalDays;
	}
};
namespace {	//namespace使下面的定义只在当前文件中有效
	//存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}

Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
	if (day <= 0 || day > getMaxDay()) {
		cout << "Invalid date: ";
		show();
		cout << endl;
		exit(1);
	}
	int years = year - 1;
	totalDays = years * 365 + years / 4 - years / 100 + years / 400
		+ DAYS_BEFORE_MONTH[month - 1] + day;
	if (isLeapYear() && month > 2) totalDays++;
}

int Date::getMaxDay() const {
	if (isLeapYear() && month == 2)
		return 29;
	else
		return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
	cout << getYear() << "-" << getMonth() << "-" << getDay();
}

class Accumulator {	//将某个数值按日累加
private:
	Date lastDate;	//上次变更数值的时期
	double value;	//数值的当前值
	double sum;		//数值按日累加之和
public:
	//构造函数,date为开始累加的日期,value为初始值
	Accumulator(const Date &date, double value)
		: lastDate(date), value(value), sum(0) { }

	//获得到日期date的累加结果
	double getSum(const Date &date) const {
		return sum + value * date.distance(lastDate);
	}

	//在date将数值变更为value
	void change(const Date &date, double value) {
		sum = getSum(date);
		lastDate = date;
		this->value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	void reset(const Date &date, double value) {
		lastDate = date;
		this->value = value;
		sum = 0;
	}
};

class Account { //账户类
private:
	std::string id;	//帐号
	double balance;	//余额
	static double total; //所有账户的总金额
protected:
	//供派生类调用的构造函数,id为账户
	Account(const Date &date, const std::string &id);
	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(const Date &date, double amount, const std::string &desc);
	//报告错误信息
	void error(const std::string &msg) const;
public:
	const std::string &getId() const { return id; }
	double getBalance() const { return balance; }
	static double getTotal() { return total; }
	//显示账户信息
	void show() const;
};

class SavingsAccount : public Account { //储蓄账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double rate;		//存款的年利率
public:
	//构造函数
	SavingsAccount(const Date &date, const std::string &id, double rate);
	double getRate() const { return rate; }
	//存入现金
	void deposit(const Date &date, double amount, const std::string &desc);
	//取出现金
	void withdraw(const Date &date, double amount, const std::string &desc);
	//结算利息,每年1月1日调用一次该函数
	void settle(const Date &date);
};

class CreditAccount : public Account { //信用账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double credit;		//信用额度
	double rate;		//欠款的日利率
	double fee;			//信用卡年费

	double getDebt() const {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}
public:
	//构造函数
	CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
	double getCredit() const { return credit; }
	double getRate() const { return rate; }
	double getFee() const { return fee; }
	double getAvailableCredit() const {	//获得可用信用
		if (getBalance() < 0)
			return credit + getBalance();
		else
			return credit;
	}
	//存入现金
	void deposit(const Date &date, double amount, const std::string &desc);
	//取出现金
	void withdraw(const Date &date, double amount, const std::string &desc);
	//结算利息和年费,每月1日调用一次该函数
	void settle(const Date &date);

	void show() const;
};

double Account::total = 0;

//Account类的实现
Account::Account(const Date &date, const string &id)
	: id(id), balance(0) {
	date.show();
	cout << "\t#" << id << " created" << endl;
}

void Account::record(const Date &date, double amount, const string &desc) {
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	date.show();
	cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void Account::show() const {
	cout << id << "\tBalance: " << balance;
}

void Account::error(const string &msg) const {
	cout << "Error(#" << id << "): " << msg << endl;
}

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
	: Account(date, id), rate(rate), acc(date, 0) { }

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getBalance());
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount > getBalance()) {
		error("not enough money");
	} else {
		record(date, -amount, desc);
		acc.change(date, getBalance());
	}
}

void SavingsAccount::settle(const Date &date) {
	double interest = acc.getSum(date) * rate	//计算年息
		/ date.distance(Date(date.getYear() - 1, 1, 1));
	if (interest != 0)
		record(date, interest, "interest");
	acc.reset(date, getBalance());
}

//CreditAccount类相关成员函数的实现
CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
	: Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { }

void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getDebt());
}

void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount - getBalance() > credit) {
		error("not enough credit");
	} else {
		record(date, -amount, desc);
		acc.change(date, getDebt());
	}
}

void CreditAccount::settle(const Date &date) {
	double interest = acc.getSum(date) * rate;
	if (interest != 0)
		record(date, interest, "interest");
	if (date.getMonth() == 1)
		record(date, -fee, "annual fee");
	acc.reset(date, getDebt());
}

void CreditAccount::show() const {
	Account::show();
	cout << "\tAvailable credit:" << getAvailableCredit();
}
int main() {
	Date date(2008, 11, 1);	//起始日期
	//建立几个账户
	SavingsAccount sa1(date, "S3755217", 0.015);
	SavingsAccount sa2(date, "02342342", 0.015);
	CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
	//11月份的几笔账目
	sa1.deposit(Date(2008, 11, 5), 5000, "salary");
	ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell");
	sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
	//结算信用卡
	ca.settle(Date(2008, 12, 1));
	//12月份的几笔账目
	ca.deposit(Date(2008, 12, 1), 2016, "repay the credit");
	sa1.deposit(Date(2008, 12, 5), 5500, "salary");
	//结算所有账户
	sa1.settle(Date(2009, 1, 1));
	sa2.settle(Date(2009, 1, 1));
	ca.settle(Date(2009, 1, 1));
	//输出各个账户信息
	cout << endl;
	sa1.show(); cout << endl;
	sa2.show(); cout << endl;
	ca.show(); cout << endl;
	cout << "Total: " << Account::getTotal() << endl;
	return 0;
}
//Accumulator.java
package SavingsAccount7_10;

class Accumulator {	//将某个数值按日累加

	private Date lastDate;	//上次变更数值的时期
	private double value;	//数值的当前值
	private double sum;		//数值按日累加之和

	//构造函数,date为开始累加的日期,value为初始值
	Accumulator(final Date date, double value){
		this.lastDate=date;
		this.value=value;
		this.sum=0;
	}

	//获得到日期date的累加结果
	final public double getSum(final Date date) {
		return sum + value * date.distance(lastDate);
	}

	//在date将数值变更为value
	public void change(final Date date, double value) {
		sum = getSum(date);
		lastDate = date;
		this.value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	public void reset(final Date date, double value) {
		lastDate = date;
		this.value = value;
		sum = 0;
	}
}

//Account.java
package SavingsAccount7_10;

class Account { //账户类
	private String id;	//帐号
	private double balance;	//余额
	private static double total=0; //所有账户的总金额
//	private final Date date;
	//供派生类调用的构造函数,id为账户
	Account(final Date date, final String id) {
		this.id=id;
		this.balance=0;
		date.show();
		System.out.println("\t#"+id+" created");
	}
	//记录一笔帐,date为日期,amount为金额,desc为说明
	protected void record(final Date date, double amount, final String desc) {
		amount = Math.floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
		balance += amount;
		total += amount;
		date.show();
		System.out.println("\t#"+id+"\t"+amount+"\t"+balance+"\t"+desc);
	}
	//报告错误信息
	protected void error(final String msg) {
		System.out.println("Error(#"+id+"): "+msg);
	}

	public final String getId() { return id; }
	public final double getBalance() { return balance; }
	public static double getTotal() { return total; }
	//显示账户信息
	public void show() {
		System.out.println(id+"\tBalance: "+balance);
	}
}

//Date.java
package SavingsAccount7_10;

class Date {	//日期类
	private int year;		//年
	private int month;		//月
	private int day;		//日
	private int totalDays;	//该日期是从公元元年1月1日开始的第几天
	private final int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

    Date(int year, int month, int day) {
		//用年、月、日构造日期
		this.year=year;
		this.month=month;
		this.day=day;
		if (day <= 0 || day > getMaxDay()) {
			System.out.println("Invalid date: ");
			show();
			System.out.println("");
			//exit(1);
		}
		int years = year - 1;
		totalDays = years * 365 + years / 4 - years / 100 + years / 400
			+ DAYS_BEFORE_MONTH[month - 1] + day;
		if (isLeapYear() && month > 2) totalDays++;
	}
    
	public final int getYear() { return year; }
	public final int getMonth()  { return month; }
	public final int getDay()  { return day; }
	public final int getMaxDay() {
		//获得当月有多少天
		if (isLeapYear() && month == 2)
			return 29;
		else
			return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
	}
	public final boolean isLeapYear() {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	public final void show() {
		//输出当前日期
		System.out.print(getYear()+"-"+getMonth()+"-"+getDay());
	}
	//计算两个日期之间差多少天
	public final int distance(final Date date) {
		return totalDays - date.totalDays;
	}
}

//SavingsAccount.java
package SavingsAccount7_10;

public class SavingsAccount extends Account { //储蓄账户类

	private Accumulator acc;	//辅助计算利息的累加器
	private double rate;		//存款的年利率

	//构造函数
	SavingsAccount(final Date date, final String id, double rate) {
		super(date,id);
		this.rate=rate;
        acc=new Accumulator(date,0);
	}
	public final double getRate() { return rate; }
	//存入现金
	public void deposit(final Date date, double amount, final String desc) {
		record(date, amount, desc);
		acc.change(date, getBalance());
	}
	//取出现金
	public void withdraw(final Date date, double amount, final String desc) {
		if (amount > getBalance()) {
			error("not enough money");
		} else {
			record(date, -amount, desc);
			acc.change(date, getBalance());
		}
	}
	//结算利息,每年1月1日调用一次该函数
	public void settle(final Date date) {
		double interest = acc.getSum(date) * rate	//计算年息
				/ date.distance(new Date(date.getYear() - 1, 1, 1));
			if (interest != 0)
				record(date, interest, "interest");
			acc.reset(date, getBalance());
	}
	
	public static void main(String[] args){
		Date date=new Date(2008, 11, 1);	//起始日期
		//建立几个账户
		SavingsAccount sa1=new SavingsAccount(date, "S3755217", 0.015);
		SavingsAccount sa2=new SavingsAccount(date, "02342342", 0.015);
		CreditAccount ca=new CreditAccount(date, "C5392394", 10000, 0.0005, 50);
		//11月份的几笔账目
		sa1.deposit(new Date(2008, 11, 5), 5000, "salary");
		ca.withdraw(new Date(2008, 11, 15), 2000, "buy a cell");
		sa2.deposit(new Date(2008, 11, 25), 10000, "sell stock 0323");
		//结算信用卡
		ca.settle(new Date(2008, 12, 1));
		//12月份的几笔账目
		ca.deposit(new Date(2008, 12, 1), 2016, "repay the credit");
		sa1.deposit(new Date(2008, 12, 5), 5500, "salary");
		//结算所有账户
		sa1.settle(new Date(2009, 1, 1));
		sa2.settle(new Date(2009, 1, 1));
		ca.settle(new Date(2009, 1, 1));
		//输出各个账户信息
		System.out.println("");
		sa1.show(); System.out.println("");
		sa2.show(); System.out.println("");
		ca.show(); System.out.println("");
		System.out.println("Total: "+Account.getTotal());
	}
}


class CreditAccount extends Account { //信用账户类

	private Accumulator acc;	//辅助计算利息的累加器
	private double credit;		//信用额度
	private double rate;		//欠款的日利率
	private double fee;			//信用卡年费

	private final double getDebt()  {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}

	//构造函数
	CreditAccount(final Date date, final String id, double credit, double rate, double fee) {
		super(date, id);
		this.credit=credit;
		this.rate=rate;
		this.fee=fee;
        acc=new Accumulator(date, 0);
	}
	public final double getCredit(){ return credit; }
	public final double getRate()  { return rate; }
	public final double getFee()  { return fee; }
	public final double getAvailableCredit()  {	//获得可用信用
		if (getBalance() < 0)
			return credit + getBalance();
		else
			return credit;
	}
	//存入现金
	public void deposit(final Date date, double amount, final String desc) {
		record(date, amount, desc);
		acc.change(date, getDebt());
	}
	//取出现金
	public void withdraw(final Date date, double amount, final String desc) {
		if (amount - getBalance() > credit) {
			error("not enough credit");
		} else {
			record(date, -amount, desc);
			acc.change(date, getDebt());
		}
	}
	//结算利息和年费,每月1日调用一次该函数
	public void settle(final Date date) {
		double interest = acc.getSum(date) * rate;
		if (interest != 0)
			record(date, interest, "interest");
		if (date.getMonth() == 1)
			record(date, -fee, "annual fee");
		acc.reset(date, getDebt());
	}

	public final void show() {
		super.show();
		System.out.println("Available credit:"+getAvailableCredit());
	}
}

运行结果:
2008-11-1       #S3755217 created
2008-11-1       #02342342 created
2008-11-1       #C5392394 created
2008-11-5       #S3755217       5000    5000    salary
2008-11-15      #C5392394       -2000   -2000   buy a cell
2008-11-25      #02342342       10000   10000   sell stock 0323
2008-12-1       #C5392394       -16     -2016   interest
2008-12-1       #C5392394       2016    0       repay the credit
2008-12-5       #S3755217       5500    10500   salary
2009-1-1        #S3755217       17.77   10517.8 interest
2009-1-1        #02342342       15.16   10015.2 interest
2009-1-1        #C5392394       -50     -50     annual fee

S3755217        Balance: 10517.8
02342342        Balance: 10015.2
C5392394        Balance: -50    Available credit:9950
Total: 20482.9

在将例7_11的C++版本代码改为Java版本的代码之中需要注意的点如下:
1.c++中指针访问使用this->value = value;,而Java中只用引用,没有指针,使用

this.value = value;

2.c++中有全局变量,但Java中没有,需要将变量的声明放在类内部。
3.c++中无名对象的传递

sa1.settle(Date(2009, 1, 1));
sa2.settle(Date(2009, 1, 1));
ca.settle(Date(2009, 1, 1));
``
Java中无名对象的传递需要使用

```cpp
sa1.settle(new Date(2009, 1, 1));
sa2.settle(new Date(2009, 1, 1));
ca.settle(new Date(2009, 1, 1));

,new之后才会产生对象。

例8_8代码:

#include <iostream>
#include <cstdlib>
#include<cmath>
using namespace std;

class Date {	//日期类
private:
	int year;		//年
	int month;		//月
	int day;		//日
	int totalDays;	//该日期是从公元元年1月1日开始的第几天

public:
	Date(int year, int month, int day);	//用年、月、日构造日期
	int getYear() const { return year; }
	int getMonth() const { return month; }
	int getDay() const { return day; }
	int getMaxDay() const;		//获得当月有多少天
	bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	void show() const;			//输出当前日期
	//计算两个日期之间差多少天
	int operator - (const Date& date) const {
		return totalDays - date.totalDays;
	}
};


namespace {	//namespace使下面的定义只在当前文件中有效
	//存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}

Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
	if (day <= 0 || day > getMaxDay()) {
		cout << "Invalid date: ";
		show();
		cout << endl;
		exit(1);
	}
	int years = year - 1;
	totalDays = years * 365 + years / 4 - years / 100 + years / 400
		+ DAYS_BEFORE_MONTH[month - 1] + day;
	if (isLeapYear() && month > 2) totalDays++;
}

int Date::getMaxDay() const {
	if (isLeapYear() && month == 2)
		return 29;
	else
		return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
	cout << getYear() << "-" << getMonth() << "-" << getDay();
}


class Accumulator {	//将某个数值按日累加
private:
	Date lastDate;	//上次变更数值的时期
	double value;	//数值的当前值
	double sum;		//数值按日累加之和
public:
	//构造函数,date为开始累加的日期,value为初始值
	Accumulator(const Date &date, double value)
		: lastDate(date), value(value), sum(0) { }

	//获得到日期date的累加结果
	double getSum(const Date &date) const {
		return sum + value * (date - lastDate);
	}

	//在date将数值变更为value
	void change(const Date &date, double value) {
		sum = getSum(date);
		lastDate = date;
		this->value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	void reset(const Date &date, double value) {
		lastDate = date;
		this->value = value;
		sum = 0;
	}
};

class Account { //账户类
private:
	std::string id;	//帐号
	double balance;	//余额
	static double total; //所有账户的总金额
protected:
	//供派生类调用的构造函数,id为账户
	Account(const Date &date, const std::string &id);
	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(const Date &date, double amount, const std::string &desc);
	//报告错误信息
	void error(const std::string &msg) const;
public:
	const std::string &getId() const { return id; }
	double getBalance() const { return balance; }
	static double getTotal() { return total; }
	//存入现金,date为日期,amount为金额,desc为款项说明
	virtual void deposit(const Date &date, double amount, const std::string &desc) = 0;
	//取出现金,date为日期,amount为金额,desc为款项说明
	virtual void withdraw(const Date &date, double amount, const std::string &desc) = 0;
	//结算(计算利息、年费等),每月结算一次,date为结算日期
	virtual void settle(const Date &date) = 0;
	//显示账户信息
	virtual void show() const;
};

class SavingsAccount : public Account { //储蓄账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double rate;		//存款的年利率
public:
	//构造函数
	SavingsAccount(const Date &date, const std::string &id, double rate);
	double getRate() const { return rate; }
	virtual void deposit(const Date &date, double amount, const std::string &desc);
	virtual void withdraw(const Date &date, double amount, const std::string &desc);
	virtual void settle(const Date &date);
};

class CreditAccount : public Account { //信用账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double credit;		//信用额度
	double rate;		//欠款的日利率
	double fee;			//信用卡年费

	double getDebt() const {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}
public:
	//构造函数
	CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
	double getCredit() const { return credit; }
	double getRate() const { return rate; }
	double getFee() const { return fee; }
	double getAvailableCredit() const {	//获得可用信用
		if (getBalance() < 0)
			return credit + getBalance();
		else
			return credit;
	}
	virtual void deposit(const Date &date, double amount, const std::string &desc);
	virtual void withdraw(const Date &date, double amount, const std::string &desc);
	virtual void settle(const Date &date);
	virtual void show() const;
};

double Account::total = 0;

//Account类的实现
Account::Account(const Date &date, const string &id)
	: id(id), balance(0) {
	date.show();
	cout << "\t#" << id << " created" << endl;
}

void Account::record(const Date &date, double amount, const string &desc) {
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	date.show();
	cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void Account::show() const {
	cout << id << "\tBalance: " << balance;
}

void Account::error(const string &msg) const {
	cout << "Error(#" << id << "): " << msg << endl;
}

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
	: Account(date, id), rate(rate), acc(date, 0) { }

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getBalance());
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount > getBalance()) {
		error("not enough money");
	} else {
		record(date, -amount, desc);
		acc.change(date, getBalance());
	}
}

void SavingsAccount::settle(const Date &date) {
	if (date.getMonth() == 1) {	//每年的一月计算一次利息
		double interest = acc.getSum(date) * rate
			/ (date - Date(date.getYear() - 1, 1, 1));
		if (interest != 0)
			record(date, interest, "interest");
		acc.reset(date, getBalance());
	}
}

//CreditAccount类相关成员函数的实现
CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
	: Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { }

void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getDebt());
}

void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount - getBalance() > credit) {
		error("not enough credit");
	} else {
		record(date, -amount, desc);
		acc.change(date, getDebt());
	}
}

void CreditAccount::settle(const Date &date) {
	double interest = acc.getSum(date) * rate;
	if (interest != 0)
		record(date, interest, "interest");
	if (date.getMonth() == 1)
		record(date, -fee, "annual fee");
	acc.reset(date, getDebt());
}

void CreditAccount::show() const {
	Account::show();
	cout << "\tAvailable credit:" << getAvailableCredit();
}


int main() {
	Date date(2008, 11, 1);	//起始日期
	//建立几个账户
	SavingsAccount sa1(date, "S3755217", 0.015);
	SavingsAccount sa2(date, "02342342", 0.015);
	CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
	Account *accounts[] = { &sa1, &sa2, &ca };
	const int n = sizeof(accounts) / sizeof(Account*);	//账户总数

	cout << "(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl;
	char cmd;
	do {
		//显示日期和总金额
		date.show();
		cout << "\tTotal: " << Account::getTotal() << "\tcommand> ";

		int index, day;
		double amount;
		string desc;

		cin >> cmd;
		switch (cmd) {
		case 'd':	//存入现金
			cin >> index >> amount;
			getline(cin, desc);
			accounts[index]->deposit(date, amount, desc);
			break;
		case 'w':	//取出现金
			cin >> index >> amount;
			getline(cin, desc);
			accounts[index]->withdraw(date, amount, desc);
			break;
		case 's':	//查询各账户信息
			for (int i = 0; i < n; i++) {
				cout << "[" << i << "] ";
				accounts[i]->show();
				cout << endl;
			}
			break;
		case 'c':	//改变日期
			cin >> day;
			if (day < date.getDay())
				cout << "You cannot specify a previous day";
			else if (day > date.getMaxDay())
				cout << "Invalid day";
			else
				date = Date(date.getYear(), date.getMonth(), day);
			break;
		case 'n':	//进入下个月
			if (date.getMonth() == 12)
				date = Date(date.getYear() + 1, 1, 1);
			else
				date = Date(date.getYear(), date.getMonth() + 1, 1);
			for (int i = 0; i < n; i++)
				accounts[i]->settle(date);
			break;
		}
	} while (cmd != 'e');
	return 0;
}

package SavingsAccount8_8;

class Accumulator {	//将某个数值按日累加
	private Date lastDate;	//上次变更数值的时期
	private double value;	//数值的当前值
	private double sum;		//数值按日累加之和
	

	//构造函数,date为开始累加的日期,value为初始值
	Accumulator(final Date date, double value){
		this.lastDate=date;
		this.value=value;
		this.sum=0;
	}

	//获得到日期date的累加结果
	final public double getSum(final Date date) {
		return sum + value * date.distance(lastDate);
	}

	//在date将数值变更为value
	public void change(final Date date, double value) {
		sum = getSum(date);
		lastDate = date;
		this.value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	public void reset(final Date date, double value) {
		lastDate = date;
		this.value = value;
		sum = 0;
	}
};

package SavingsAccount8_8;

class Account { //账户类
	private String id;	//帐号
	private double balance;	//余额
	private static double total=0; //所有账户的总金额
	
	Account(final Date date, final String id) {
		this.id=id;
		this.balance=0;
		date.show();
		System.out.println("\t#"+id+" created");
	}
	//记录一笔帐,date为日期,amount为金额,desc为说明
	protected void record(final Date date, double amount, final String desc) {
		amount = Math.floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
		balance += amount;
		total += amount;
		date.show();
		System.out.println("\t#"+id+"\t"+amount+"\t"+balance+"\t"+desc);
	}
	//报告错误信息
	protected void error(final String msg) {
		System.out.println("Error(#"+id+"): "+msg);
	}

	public final String getId() { return id; }
	public final double getBalance() { return balance; }
	public static double getTotal() { return total; }
    public void deposit(final Date date, double amount, final String desc) {
    	
    }
	//取出现金,date为日期,amount为金额,desc为款项说明
    public void withdraw(final Date date, double amount, final String desc) {
    	
    }
	//结算(计算利息、年费等),每月结算一次,date为结算日期
    public void settle(final Date date) {
    	
    }
	//显示账户信息
	//显示账户信息
	public void show() {
		System.out.println(id+"\tBalance: "+balance);
	}
	
};

package SavingsAccount8_8;

class CreditAccount extends Account { //信用账户类
	private Accumulator acc;	//辅助计算利息的累加器
	private double credit;		//信用额度
	private double rate;		//欠款的日利率
	private double fee;			//信用卡年费

	private final double getDebt()  {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}
	

	//构造函数
	CreditAccount(final Date date, final String id, double credit, double rate, double fee) {
		super(date, id);
		this.credit=credit;
		this.rate=rate;
		this.fee=fee;
        acc=new Accumulator(date, 0);
	}
	public final double getCredit(){ return credit; }
	public final double getRate()  { return rate; }
	public final double getFee()  { return fee; }
	public final double getAvailableCredit()  {	//获得可用信用
		if (getBalance() < 0)
			return credit + getBalance();
		else
			return credit;
	}
	//存入现金
	public void deposit(final Date date, double amount, final String desc) {
		record(date, amount, desc);
		acc.change(date, getDebt());
	}
	//取出现金
	public void withdraw(final Date date, double amount, final String desc) {
		if (amount - getBalance() > credit) {
			error("not enough credit");
		} else {
			record(date, -amount, desc);
			acc.change(date, getDebt());
		}
	}
	//结算利息和年费,每月1日调用一次该函数
	public void settle(final Date date) {
		double interest = acc.getSum(date) * rate;
		if (interest != 0)
			record(date, interest, "interest");
		if (date.getMonth() == 1)
			record(date, -fee, "annual fee");
		acc.reset(date, getDebt());
	}

	public final void show() {
		super.show();
		System.out.println("Available credit:"+getAvailableCredit());
	}
};

package SavingsAccount8_8;

class Date {	//日期类
	private int year;		//年
	private int month;		//月
	private int day;		//日
	private int totalDays;	//该日期是从公元元年1月1日开始的第几天
	private final int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };


	Date(int year, int month, int day) {
		//用年、月、日构造日期
		this.year=year;
		this.month=month;
		this.day=day;
		if (day <= 0 || day > getMaxDay()) {
			System.out.println("Invalid date: ");
			show();
			System.out.println("");
			//exit(1);
		}
		int years = year - 1;
		totalDays = years * 365 + years / 4 - years / 100 + years / 400
			+ DAYS_BEFORE_MONTH[month - 1] + day;
		if (isLeapYear() && month > 2) totalDays++;
	}
	public final int getYear() { return year; }
	public final int getMonth()  { return month; }
	public final int getDay()  { return day; }
	public final int getMaxDay() {
		//获得当月有多少天
		if (isLeapYear() && month == 2)
			return 29;
		else
			return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
	}
	public final boolean isLeapYear() {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	public final void show() {
		//输出当前日期
		System.out.print(getYear()+"-"+getMonth()+"-"+getDay());
	}
	//计算两个日期之间差多少天
	//java没有运算符的重载,需要些函数来实现相应功能
	public final int distance(final Date date) {
		return totalDays - date.totalDays;
	}
};

package SavingsAccount8_8;

import java.io.IOException;
import java.io.InputStreamReader;    
import java.util.Scanner;    


class SavingsAccount extends Account { private static final Scanner Scanner = null;
//储蓄账户类
	private Accumulator acc;	//辅助计算利息的累加器
	private double rate;		//存款的年利率
	
	SavingsAccount(final Date date, final String id, double rate) {
		super(date,id);
		this.rate=rate;
      acc=new Accumulator(date,0);
	}
	public final double getRate() { return rate; }
	//存入现金
	public void deposit(final Date date, double amount, final String desc) {
		record(date, amount, desc);
		acc.change(date, getBalance());
	}
	//取出现金
	public void withdraw(final Date date, double amount, final String desc) {
		if (amount > getBalance()) {
			error("not enough money");
		} else {
			record(date, -amount, desc);
			acc.change(date, getBalance());
		}
	}
	//结算利息,每年1月1日调用一次该函数

	public void settle(final Date date) {
		double interest = acc.getSum(date) * rate	//计算年息
				/ date.distance(new Date(date.getYear() - 1, 1, 1));
			if (interest != 0)
				record(date, interest, "interest");
			acc.reset(date, getBalance());
	}
	
	
	public static void main(String[] args) throws IOException{
		Date date=new Date(2008, 11, 1);	//起始日期
		//建立几个账户
		SavingsAccount sa1=new SavingsAccount(date, "S3755217", 0.015);
		SavingsAccount sa2=new SavingsAccount(date, "02342342", 0.015);
		CreditAccount ca=new CreditAccount(date, "C5392394", 10000, 0.0005, 50);
		
		Account accounts[] = { sa1, sa2, ca };
		final int n =accounts.length;	//账户总数

		System.out.println("(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit");
		String cmd;
		Scanner sc = new Scanner(System.in);
		Scanner in = new Scanner(System.in);
		
		do {
			
			date.show();
			System.out.print("\tTotal: "+Account.getTotal()+"\tcommand ");
			int index, day;
			double amount;
			String desc = null;
			//char c=(char)System.in.read();  
			//cmd = (char)System.in.read();
			//BufferedReader cmd = new BufferedReader(new InputStreamReader(System.in));
			cmd=in.next();
			switch (cmd) {
			
			case "d":	//存入现金
				index = sc.nextInt();  //读取整型输入   
				amount = sc.nextDouble();  //读取float型输入
				//cin >> index >> amount;
				
				getline(Scanner, desc);
				
				accounts[index].deposit(date, amount, desc);
				break;
			case "w":	//取出现金
				index = sc.nextInt();  //读取整型输入   
				amount = sc.nextDouble();  //读取float型输入
				getline(sc, desc);
				accounts[index].withdraw(date, amount, desc);
				break;
			case "s":	//查询各账户信息
				for (int i = 0; i < n; i++) {
					System.out.print("["+i +"]");
					accounts[i].show();
					System.out.print("");
				}
				break;
			case "c":	//改变日期
				day = sc.nextInt();  //读取整型输入   
				if (day < date.getDay())
					System.out.println("You cannot specify a previous day");
				else if (day > date.getMaxDay())
					System.out.println("Invalid day");
				else
					date = new Date(date.getYear(), date.getMonth(), day);
				break;
			case "n":	//进入下个月
				if (date.getMonth() == 12)
					date = new Date(date.getYear() + 1, 1, 1);
				else
					date = new Date(date.getYear(), date.getMonth() + 1, 1);
				for (int i = 0; i < n; i++)
					accounts[i].settle(date);
				break;
			}
		} while (cmd != "e");
	}
	private static void getline(Scanner sc, String desc) {
		// TODO Auto-generated method stub
	}
};

运行结果
2008-11-1       #S3755217 created
2008-11-1       #02342342 created
2008-11-1       #C5392394 created
(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit
2008-11-1       Total: 0        command> d
0 1000
2008-11-1       #S3755217       1000    1000
2008-11-1       Total: 1000     command> d
1 1000
2008-11-1       #02342342       1000    1000
2008-11-1       Total: 2000     command> d
2 2000
2008-11-1       #C5392394       2000    2000
2008-11-1       Total: 4000     command> s
[0] S3755217    Balance: 1000
[1] 02342342    Balance: 1000
[2] C5392394    Balance: 2000   Available credit:10000
2008-11-1       Total: 4000     command> w
2 800
2008-11-1       #C5392394       -800    1200
2008-11-1       Total: 3200     command> w
0 700
2008-11-1       #S3755217       -700    300
2008-11-1       Total: 2500     command> w
1 600
2008-11-1       #02342342       -600    400
2008-11-1       Total: 1900     command> s
[0] S3755217    Balance: 300
[1] 02342342    Balance: 400
[2] C5392394    Balance: 1200   Available credit:10000
2008-11-1       Total: 1900     command> c
12
2008-11-12      Total: 1900     command> s
[0] S3755217    Balance: 300
[1] 02342342    Balance: 400
[2] C5392394    Balance: 1200   Available credit:10000
2008-11-12      Total: 1900     command> n
2008-12-1       Total: 1900     command> n
2009-1-1        #S3755217       0.75    300.75  interest
2009-1-1        #02342342       1       401     interest
2009-1-1        #C5392394       -50     1150    annual fee
2009-1-1        Total: 1851.75  command> n
2009-2-1        Total: 1851.75  command> n
2009-3-1        Total: 1851.75  command> n
2009-4-1        Total: 1851.75  command> n
2009-5-1        Total: 1851.75  command> e

例9_16

//date.h
#ifndef __DATE_H__
#define __DATE_H__

class Date {	//日期类
private:
	int year;		//年
	int month;		//月
	int day;		//日
	int totalDays;	//该日期是从公元元年1月1日开始的第几天

public:
	Date(int year, int month, int day);	//用年、月、日构造日期
	int getYear() const { return year; }
	int getMonth() const { return month; }
	int getDay() const { return day; }
	int getMaxDay() const;		//获得当月有多少天
	bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	void show() const;			//输出当前日期
	//计算两个日期之间差多少天	
	int operator - (const Date& date) const {
		return totalDays - date.totalDays;
	}
};

#endif //__DATE_H__

//accumulator.h
#ifndef __ACCUMULATOR_H__
#define __ACCUMULATOR_H__
#include "date.h"

class Accumulator {	//将某个数值按日累加
private:
	Date lastDate;	//上次变更数值的时期
	double value;	//数值的当前值
	double sum;		//数值按日累加之和
public:
	//构造函数,date为开始累加的日期,value为初始值
	Accumulator(const Date &date, double value)
		: lastDate(date), value(value), sum(0) { }

	//获得到日期date的累加结果
	double getSum(const Date &date) const {
		return sum + value * (date - lastDate);
	}

	//在date将数值变更为value
	void change(const Date &date, double value) {
		sum = getSum(date);
		lastDate = date;
		this->value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	void reset(const Date &date, double value) {
		lastDate = date;
		this->value = value;
		sum = 0;
	}
};

#endif //__ACCUMULATOR_H__

//date.cpp
#include "date.h"
#include <iostream>
#include <cstdlib>
using namespace std;

namespace {	//namespace使下面的定义只在当前文件中有效
	//存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}

Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
	if (day <= 0 || day > getMaxDay()) {
		cout << "Invalid date: ";
		show();
		cout << endl;
		exit(1);
	}
	int years = year - 1;
	totalDays = years * 365 + years / 4 - years / 100 + years / 400
		+ DAYS_BEFORE_MONTH[month - 1] + day;
	if (isLeapYear() && month > 2) totalDays++;
}

int Date::getMaxDay() const {
	if (isLeapYear() && month == 2)
		return 29;
	else
		return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
	cout << getYear() << "-" << getMonth() << "-" << getDay();
}

//account.cpp
#include "account.h"
#include <cmath>
#include <iostream>
using namespace std;

double Account::total = 0;

//Account类的实现
Account::Account(const Date &date, const string &id)
	: id(id), balance(0) {
	date.show();
	cout << "\t#" << id << " created" << endl;
}

void Account::record(const Date &date, double amount, const string &desc) {
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	date.show();
	cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void Account::show() const {
	cout << id << "\tBalance: " << balance;
}

void Account::error(const string &msg) const {
	cout << "Error(#" << id << "): " << msg << endl;
}

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
	: Account(date, id), rate(rate), acc(date, 0) { }

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getBalance());
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount > getBalance()) {
		error("not enough money");
	} else {
		record(date, -amount, desc);
		acc.change(date, getBalance());
	}
}

void SavingsAccount::settle(const Date &date) {
	if (date.getMonth() == 1) {	//每年的一月计算一次利息
		double interest = acc.getSum(date) * rate
			/ (date - Date(date.getYear() - 1, 1, 1));
		if (interest != 0)
			record(date, interest, "interest");
		acc.reset(date, getBalance());
	}
}

//CreditAccount类相关成员函数的实现
CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
	: Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { }

void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getDebt());
}

void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount - getBalance() > credit) {
		error("not enough credit");
	} else {
		record(date, -amount, desc);
		acc.change(date, getDebt());
	}
}

void CreditAccount::settle(const Date &date) {
	double interest = acc.getSum(date) * rate;
	if (interest != 0)
		record(date, interest, "interest");
	if (date.getMonth() == 1)
		record(date, -fee, "annual fee");
	acc.reset(date, getDebt());
}

void CreditAccount::show() const {
	Account::show();
	cout << "\tAvailable credit:" << getAvailableCredit();
}

//account.h
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
#include "date.h"
#include "accumulator.h"
#include <string>

class Account { //账户类
private:
	std::string id;	//帐号
	double balance;	//余额
	static double total; //所有账户的总金额
protected:
	//供派生类调用的构造函数,id为账户
	Account(const Date &date, const std::string &id);
	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(const Date &date, double amount, const std::string &desc);
	//报告错误信息
	void error(const std::string &msg) const;
public:
	const std::string &getId() const { return id; }
	double getBalance() const { return balance; }
	static double getTotal() { return total; }
	//存入现金,date为日期,amount为金额,desc为款项说明
	virtual void deposit(const Date &date, double amount, const std::string &desc) = 0;
	//取出现金,date为日期,amount为金额,desc为款项说明
	virtual void withdraw(const Date &date, double amount, const std::string &desc) = 0;
	//结算(计算利息、年费等),每月结算一次,date为结算日期
	virtual void settle(const Date &date) = 0;
	//显示账户信息
	virtual void show() const;
};

class SavingsAccount : public Account { //储蓄账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double rate;		//存款的年利率
public:
	//构造函数
	SavingsAccount(const Date &date, const std::string &id, double rate);
	double getRate() const { return rate; }
	virtual void deposit(const Date &date, double amount, const std::string &desc);
	virtual void withdraw(const Date &date, double amount, const std::string &desc);
	virtual void settle(const Date &date);
};

class CreditAccount : public Account { //信用账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double credit;		//信用额度
	double rate;		//欠款的日利率
	double fee;			//信用卡年费

	double getDebt() const {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}
public:
	//构造函数
	CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
	double getCredit() const { return credit; }
	double getRate() const { return rate; }
	double getFee() const { return fee; }
	double getAvailableCredit() const {	//获得可用信用
		if (getBalance() < 0) 
			return credit + getBalance();
		else
			return credit;
	}
	virtual void deposit(const Date &date, double amount, const std::string &desc);
	virtual void withdraw(const Date &date, double amount, const std::string &desc);
	virtual void settle(const Date &date);
	virtual void show() const;
};

#endif //__ACCOUNT_H__

//9_16.cpp
#include "account.h"
#include "Array.h"
#include <iostream>
using namespace std;

int main() {
	Date date(2008, 11, 1);	//起始日期
	Array<Account *> accounts(0);	//创建账户数组,元素个数为0
	cout << "(a)add account (d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl;
	char cmd;
	do {
		//显示日期和总金额
		date.show();
		cout << "\tTotal: " << Account::getTotal() << "\tcommand> ";

		char type;
		int index, day;
		double amount, credit, rate, fee;
		string id, desc;
		Account* account;

		cin >> cmd;
		switch (cmd) {
		case 'a':	//增加账户
			cin >> type >> id;
			if (type == 's') {
				cin >> rate;
				account = new SavingsAccount(date, id, rate);
			} else {
				cin >> credit >> rate >> fee;
				account = new CreditAccount(date, id, credit, rate, fee);
			}
			accounts.resize(accounts.getSize() + 1);
			accounts[accounts.getSize() - 1] = account;
			break;
		case 'd':	//存入现金
			cin >> index >> amount;
			getline(cin, desc);
			accounts[index]->deposit(date, amount, desc);
			break;
		case 'w':	//取出现金
			cin >> index >> amount;
			getline(cin, desc);
			accounts[index]->withdraw(date, amount, desc);
			break;
		case 's':	//查询各账户信息
			for (int i = 0; i < accounts.getSize(); i++) {
				cout << "[" << i << "] ";
				accounts[i]->show();
				cout << endl;
			}
			break;
		case 'c':	//改变日期
			cin >> day;
			if (day < date.getDay())
				cout << "You cannot specify a previous day";
			else if (day > date.getMaxDay())
				cout << "Invalid day";
			else
				date = Date(date.getYear(), date.getMonth(), day);
			break;
		case 'n':	//进入下个月
			if (date.getMonth() == 12)
				date = Date(date.getYear() + 1, 1, 1);
			else
				date = Date(date.getYear(), date.getMonth() + 1, 1);
			for (int i = 0; i < accounts.getSize(); i++)
				accounts[i]->settle(date);
			break;
		}
	} while (cmd != 'e');

	for (int i = 0; i < accounts.getSize(); i++)
		delete accounts[i];

	return 0;
}

//Array.h
#ifndef ARRAY_H
#define ARRAY_H

#include <cassert>

//数组类模板定义
template <class T> 
class Array {
private:
	T* list;	//T类型指针,用于存放动态分配的数组内存首地址
	int size;	//数组大小(元素个数)
public:
	Array(int sz = 50);			//构造函数
	Array(const Array<T> &a);	//拷贝构造函数
	~Array();	//析构函数
	Array<T> & operator = (const Array<T> &rhs); //重载"="使数组对象可以整体赋值
	T & operator [] (int i);	//重载"[]",使Array对象可以起到C++普通数组的作用
	const T & operator [] (int i) const;	//"[]"运算符的const版本
	operator T * ();	//重载到T*类型的转换,使Array对象可以起到C++普通数组的作用
	operator const T * () const;	//到T*类型转换操作符的const版本
	int getSize() const;	//取数组的大小
	void resize(int sz);	//修改数组的大小
};

//构造函数
template <class T>
Array<T>::Array(int sz) {
	assert(sz >= 0);	//sz为数组大小(元素个数),应当非负
	size = sz;	// 将元素个数赋值给变量size
	list = new T [size];	//动态分配size个T类型的元素空间
}

//析构函数
template <class T>
Array<T>::~Array() {
	delete [] list;
}

//拷贝构造函数
template <class T>
Array<T>::Array(const Array<T> &a) {
	//从对象x取得数组大小,并赋值给当前对象的成员
	size = a.size;
	//为对象申请内存并进行出错检查
	list = new T[size];	// 动态分配n个T类型的元素空间
	//从对象X复制数组元素到本对象  
	for (int i = 0; i < size; i++)
		list[i] = a.list[i];
}

//重载"="运算符,将对象rhs赋值给本对象。实现对象之间的整体赋值
template <class T>
Array<T> &Array<T>::operator = (const Array<T>& rhs) {
	if (&rhs != this) {
		//如果本对象中数组大小与rhs不同,则删除数组原有内存,然后重新分配
		if (size != rhs.size) {
			delete [] list;		//删除数组原有内存
			size = rhs.size;	//设置本对象的数组大小
			list = new T[size];	//重新分配n个元素的内存
		}
		//从对象X复制数组元素到本对象  
		for (int i = 0; i < size; i++)
			list[i] = rhs.list[i];
	}
	return *this;	//返回当前对象的引用
}

//重载下标运算符,实现与普通数组一样通过下标访问元素,并且具有越界检查功能
template <class T>
T &Array<T>::operator[] (int n) {
	assert(n >= 0 && n < size);	//检查下标是否越界
	return list[n];			//返回下标为n的数组元素
}

template <class T>
const T &Array<T>::operator[] (int n) const {
	assert(n >= 0 && n < size);	//检查下标是否越界
	return list[n];			//返回下标为n的数组元素
}

//重载指针转换运算符,将Array类的对象名转换为T类型的指针,
//指向当前对象中的私有数组。
//因而可以象使用普通数组首地址一样使用Array类的对象名
template <class T>
Array<T>::operator T * () {
	return list;	//返回当前对象中私有数组的首地址
}

template <class T>
Array<T>::operator const T * () const {
	return list;	//返回当前对象中私有数组的首地址
}

//取当前数组的大小
template <class T>
int Array<T>::getSize() const {
	return size;
}

// 将数组大小修改为sz
template <class T>
void Array<T>::resize(int sz) {
	assert(sz >= 0);	//检查sz是否非负
	if (sz == size)	//如果指定的大小与原有大小一样,什么也不做
		return;
	T* newList = new T [sz];	//申请新的数组内存
	int n = (sz < size) ? sz : size;	//将sz与size中较小的一个赋值给n
	//将原有数组中前n个元素复制到新数组中
	for (int i = 0; i < n; i++)
		newList[i] = list[i];
	delete[] list;		//删除原数组
	list = newList;	// 使list指向新数组
	size = sz;	//更新size
}
#endif  //ARRAY_H

Java版本

package bank11;

public class Accumulator {
	private Date lastDate;	//上次变更数值的时期
	private double value;	//数值的当前值
	private double sum;		//数值按日累加之和
	

	//构造函数,date为开始累加的日期,value为初始值
	public Accumulator(final Date date, double value){
		this.lastDate=date;
		this.value=value;
		this.sum=0;
	}

	//获得到日期date的累加结果
	public final double getSum(final Date date) {
		return sum + value * date.distance(lastDate);
	}

	//在date将数值变更为value
	public void change(final Date date, double value) {
		sum = getSum(date);
		lastDate = date;
		this.value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	public void reset(final Date date, double value) {
		lastDate = date;
		this.value = value;
		sum = 0;
	}


package bank11;

public class Account {
	private String id;	//帐号
	private double balance;	//余额
	private static double total=0; //所有账户的总金额

	//供派生类调用的构造函数,id为账户
	protected Account(final Date date, final String id){
		this.id=id;
		this.balance=0;
		System.out.println("\t#"+id+" created");
	}
	//记录一笔帐,date为日期,amount为金额,desc为说明
	protected void record(final Date date, double amount, final String desc){
		amount = Math.floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
		balance += amount;
		total += amount;
		date.show();
		System.out.println("\t#"+id+"\t"+amount+"\t"+balance+"\t"+desc);
	}
	//报告错误信息
	protected final void error(final String msg) {
		System.out.println("Error(#"+id+"): "+msg);
	}

	public final String getId() { return id; }
	public final double getBalance() { return balance; }
	public static double getTotal() { return total; }
	//存入现金,date为日期,amount为金额,desc为款项说明
	public void deposit(final Date date, double amount, final String desc){
		
	}
	//取出现金,date为日期,amount为金额,desc为款项说明
	public void withdraw(final Date date, double amount, final String desc){
		
	}
	//结算(计算利息、年费等),每月结算一次,date为结算日期
	public void settle(final Date date) {
		
	}
	//显示账户信息
	public void show(){
		System.out.print(id+"\tBalance: "+balance);
	}
}

package bank11;

public class CreditAccount extends Account{
	private Accumulator acc;	//辅助计算利息的累加器
	private double credit;		//信用额度
	private double rate;		//欠款的日利率
	private double fee;			//信用卡年费

	private final double getDebt()  {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}

	//构造函数
	CreditAccount(final Date date, final String id, double credit, double rate, double fee){
		super(date,id);
		this.credit=credit;
		this.rate=rate;
		this.fee=fee;
		acc=new Accumulator(date,0);
	}
	public final double getCredit()  { return credit; }
	public final double getRate()  { return rate; }
	public final double getFee()  { return fee; }
	public final double getAvailableCredit()  {	//获得可用信用
		if (getBalance() < 0) 
			return credit + getBalance();
		else
			return credit;
	}
	public void deposit(final Date date, double amount,final String desc){
		record(date, amount, desc);
		acc.change(date, getDebt());
	}
	public void withdraw(final Date date, double amount, final String desc){
		if (amount - getBalance() > credit) {
			error("not enough credit");
		} else {
			record(date, -amount, desc);
			acc.change(date, getDebt());
		}
	}
	public void settle(final Date date){
		double interest = acc.getSum(date) * rate;
		if (interest != 0)
			record(date, interest, "interest");
		if (date.getMonth() == 1)
			record(date, -fee, "annual fee");
		acc.reset(date, getDebt());
	}
	public final void show() {
		super.show();
		System.out.print("\tAvailable credit:"+getAvailableCredit());
	}

}

package bank11;

public class Date {
	private int year;		//年
	private int month;		//月
	private int day;		//日
	private int totalDays;	//该日期是从公元元年1月1日开始的第几天
	private final  int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };


	public Date(int year, int month, int day){
		//用年、月、日构造日期
		this.year=year;
		this.month=month;
		this.day=day;
		
		if (day <= 0 || day > getMaxDay()) {
			System.out.println("Invalid date: ");
			show();
			System.out.println("");
			System.exit(1);//exit(1);
		}
		int years = year - 1;
		totalDays = years * 365 + years / 4 - years / 100 + years / 400
			+ DAYS_BEFORE_MONTH[month - 1] + day;
		if (isLeapYear() && month > 2) 
			totalDays++;
	}
	public final int getYear()  { return year; }
	public final int getMonth()  { return month; }
	public final int getDay()  { return day; }
	public final int getMaxDay() {
		//获得当月有多少天
		if (isLeapYear() && month == 2)
			return 29;
		else
			return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
	}
	public final boolean isLeapYear()  {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	public final void show() {
		//输出当前日期
		System.out.println(getYear()+"-"+getMonth()+"-"+getDay());
	}
	//计算两个日期之间差多少天	
	public final int  distance(final Date date) {
		return totalDays - date.totalDays;
	}
}

package bank11;

import java.util.Scanner;    
import java.util.ArrayList;


class SavingsAccount extends Account { //储蓄账户类

	private Accumulator acc;	//辅助计算利息的累加器
	private double rate;		//存款的年利率

	//构造函数
	public SavingsAccount(final Date date, final String id, double rate){
		super(date, id);
		this.rate=rate;
		acc=new Accumulator(date,0);//创建对象
	}
	public final double getRate() { return rate; }
	public void deposit(final Date date, double amount,final String desc){
		record(date, amount, desc);
		acc.change(date, getBalance());
	}
	public void withdraw(final Date date, double amount,final String desc){
		if (amount > getBalance()) {
			error("not enough money");
		} else {
			record(date, -amount, desc);
			acc.change(date, getBalance());
		}
	}
	public void settle(final Date date){
		if (date.getMonth() == 1) {	//每年的一月计算一次利息
			double interest = acc.getSum(date) * rate
				/(date.distance(new Date(date.getYear() - 1, 1, 1)));//要new一个对象
			if (interest != 0)
				record(date, interest, "interest");
			acc.reset(date, getBalance());
		}
	}
	
	
	public static void main(String[] args) {
		Date date=new Date(2008, 11, 1);	//起始日期
		ArrayList<Account> accounts=new ArrayList<Account>(0);	//创建账户数组,元素个数为0
	    System.out.println("(a)add account (d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit");
		char cmd;
		do {
			//显示日期和总金额
			date.show();
		    System.out.println("\tTotal: "+Account.getTotal()+"\tcommand> ");

			char type;
			int index, day;
			double amount, credit, rate, fee;
			String id, desc;
			Account account;
			
			Scanner sc = new Scanner(System.in);
			String s = sc.next();
            cmd= s.charAt(0);
			switch (cmd) {
			case 'a':	//增加账户
				String m = sc.next();
	            type= m.charAt(0);
			    id=sc.next();
				if (type == 's') {
					rate=sc.nextDouble();
					account = new SavingsAccount(date, id, rate);
				} else {
					credit=sc.nextDouble(); 
					rate=sc.nextDouble();
					fee=sc.nextDouble();
					account = new CreditAccount(date, id, credit, rate, fee);
				    accounts.add(new CreditAccount(date, id, credit, rate, fee));
				}
				break;
			case 'd':	//存入现金
				index=sc.nextInt();
				amount=sc.nextDouble();
				desc=sc.nextLine();
				accounts.get(index).deposit(date, amount, desc);
				break;
			case 'w':	//取出现金
				index=sc.nextInt();
				amount=sc.nextDouble();
				desc=sc.nextLine();
				accounts.get(index).withdraw(date, amount, desc);
				break;
			case 's':	//查询各账户信息
				for (int i = 0; i < accounts.size(); i++) {
					System.out.println("["+i+"] ");
					accounts.get(i).show();
					System.out.println("");
				}
				break;
			case 'c':	//改变日期
				day=sc.nextInt();
				if (day < date.getDay())
					System.out.println("You cannot specify a previous day");
				else if (day > date.getMaxDay())
					System.out.println("Invalid day");
				else
					date = new Date(date.getYear(), date.getMonth(), day);
				break;
			case 'n':	//进入下个月
				if (date.getMonth() == 12)
					date = new Date(date.getYear() + 1, 1, 1);
				else
					date = new Date(date.getYear(), date.getMonth() + 1, 1);
				for (int i = 0; i < accounts.size(); i++)
					accounts.get(i).settle(date);
				break;
			}
		} while (cmd != 'e');

		for (int i = 0; i < accounts.size(); i++)
		        accounts.clear();

	}
	

	
}


1.Java中没有运算符重载,故需要另写函数来支持相关功能。
2.Java中中的泛型可以使用ArrayList来实现。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值