创建savingsAccount类。使用static数据成员来包含每个存款人的annualInterestRate(利率)。类的每个成员包含private数据成员savingsBalance,它说明了存款账户上现有的余额。提供calculateMothlyInterest成员函数,它通过将savingsBalance乘以annualInterestRate并除以12来计算每个月的利息,这个利息应该添加到savingsBalance上。
以(0.3,5000)和(0.4,8000)为例,输出两个对象dep1,dep2的余额和利息。
//作为小白,探索这个做法的时候,了解了相关知识:
//1、static静态成员变量的作用和用法(使用static来修饰成员变量的时候,要在.cpp文件里面先初始化)
//2、只有构造函数才可用初始化列表
//3、构造函数是和类同名的函数
//做题过程中思路:
//完成基本要素创建之后,需要思考函数定义
//一共有两个函数,一个是calculateMothlyInterest 计算余额的终值,一个需要输入savingsBalance 和annualInterestRate的值
//因此完成函数定义和声明
具体代码如下
//savingAccount.h
#pragma once
class savingAccount
{
double savingsBalance;
static double annualInterestRate;
public:
double calculateMothlyInterest();
void Set_interest_balance(double x, double y) ;
};
//savingAccount.cpp
#include "savingAccount.h"
double savingAccount::annualInterestRate;//用了static,就需要在类外进行初始化,不用再写static
double savingAccount::calculateMothlyInterest()
{
savingsBalance+= savingsBalance * annualInterestRate / 12;
// TODO: 在此处添加实现代码.
return savingsBalance;
}
void savingAccount::Set_interest_balance(double x, double y)
{
annualInterestRate = x;
savingsBalance = y;
// TODO: 在此处添加实现代码.
}
//main.cpp
#include<iostream>
using namespace std;
#include "savingAccount.h"
int main()
{
savingAccount dep1, dep2;
dep1.Set_interest_balance(0.3, 5000);
dep2.Set_interest_balance(0.4, 8000);
cout << "dep1 余额是" << dep1.calculateMothlyInterest() << endl;
cout << "dep2 余额是" << dep2.calculateMothlyInterest() << endl;
return 0;
}