对于静态成员函数和静态成员变量的练习

/*生成一个SavingAccount类,用static数据成员包含每个存款人的annualInerestRate(年利率)。类的每个成员包含一个private数据成员savingsBalance,表示
当前存款额。提供一个calculateMonthlyInterest成员函数,计算月利息,用balance乘以annualInerestRate除以12取得,并将这个月息加进savingsBalance。
提供一个static成员函数modifyInterestRate,将static annualInerestRate设置为新值。实例化两个不同的SavingsAccount对象saver1和saver2,结余分别为
2000.00和3000.00。将annualInerestRate设置为3%,计算每个存款人的月息并打印新的结果。然后将annualInerestRate设置为4%,再次计算每个存款人的月息
并打印新的结果*/


#include<iostream>
using namespace std;
class SavingAccount{
private:
 static double annualInerestRate;
 double savingsBalance;//表示当前存款余额
public:
 SavingAccount(double x=0.00)
 {
  savingsBalance=x;
 }
 void calculateMonthlyInterest()
 {
  savingsBalance = savingsBalance + (savingsBalance*annualInerestRate)/12;
 }
 static void modifyInterestRate(SavingAccount &ob,double x)
 {
  ob.annualInerestRate=x;
  //annualInerestRate=x;
 }
 void print()
 {
  cout<<"该客户的账户余额是:"<< savingsBalance <<endl;
 }

};
double SavingAccount::annualInerestRate=0.03;
void main()
{
 SavingAccount saver1(2000.00),saver2(3000.00);
 saver1.calculateMonthlyInterest();
 saver2.calculateMonthlyInterest();
 saver1.print();
 saver2.print();

 SavingAccount::modifyInterestRate(saver1,0.04);
 saver1.calculateMonthlyInterest();
 saver2.calculateMonthlyInterest();
 saver1.print();
 saver2.print();
}

/*我对于静态成员函数的思考,它是独立于对象而存在的,我刚开始定义设置年利率那个函数时,对它的参数个数有一番犹豫,因为
它既然是独立于对象存在,那么就不用写明是哪个对象,但是,如果不写明的话,也没有报错,在这里是因为没有涉及到处理非静态成员
,所以我认为一般情况下最好写清楚它是用哪个对象调用,以防出错*/

原文地址:https://www.cnblogs.com/javaadu/p/11742819.html