C++ examples for Class:static member
Use a static data member to track the annual interest rate for each of the savers.
#include <iostream> class SavingsAccount { public://from w ww. j a v a 2s . c o m explicit SavingsAccount(double, double = 0.0f); void calculateMonthlyInterest(); static void modifyInterestRate(double); static double getInterestRate(); friend std::ostream& operator<<(std::ostream& out, SavingsAccount acc) { return acc.printBalance(out); } std::ostream& printBalance(std::ostream&) const; private: static double annualInterestRate; double savingsBalance; }; #include <stdexcept> double SavingsAccount::annualInterestRate = 0.0f; SavingsAccount::SavingsAccount(double bal, double rte) : savingsBalance(bal) { try { modifyInterestRate(rte); } catch (std::invalid_argument& e) { std::cout << "Unable to initialize object: " << e.what() << std::endl; } } void SavingsAccount::calculateMonthlyInterest() { savingsBalance += ((savingsBalance * annualInterestRate) / 12.0f); } double SavingsAccount::getInterestRate() { return annualInterestRate; } void SavingsAccount::modifyInterestRate(double rte) { if (rte >= 0.0f) annualInterestRate = rte; else throw std::invalid_argument("Interest rate cannot be negative"); } std::ostream& SavingsAccount::printBalance(std::ostream& out) const { out << savingsBalance; return out; } int main(int argc, const char* argv[]) { SavingsAccount saver1(2000.00f); SavingsAccount saver2(3000.00f, 0.03f); SavingsAccount saver3(5000.00f, -0.12f); std::cout << "Interest rate at 3%" << std::endl; std::cout << "saver1 initial balance: " << saver1 << std::endl; saver1.calculateMonthlyInterest(); std::cout << "after calculateInterestRate " << saver1 << std::endl; std::cout << "saver2 initial balance: " << saver2 << std::endl; saver2.calculateMonthlyInterest(); std::cout << "after calculateInterestRate " << saver2 << std::endl; SavingsAccount::modifyInterestRate(0.04f); std::cout << "\nInterest rate at 4%" << std::endl; std::cout << "saver1 initial balance: " << saver1 << std::endl; saver1.calculateMonthlyInterest(); std::cout << "after calculateInterestRate " << saver1 << std::endl; std::cout << "saver2 initial balance: " << saver2 << std::endl; saver2.calculateMonthlyInterest(); std::cout << "after calculateInterestRate " << saver2 << std::endl; try { SavingsAccount::modifyInterestRate(-0.12f); } catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } return 0; }