7.6 類靜態成員

書中頁數:P268
代碼名稱:Account.h Account.cc useAccount.cc

// Account.h 
#ifndef ACCOUNT_H
#define ACCOUNT_H

#include <string>

class Account {
public:
	Account() = default;
	Account(const std::string &s, double amt):
		owner(s), amount(amt) { }

    void calculate() { amount += amount * interestRate; }
    double balance() { return amount; }
public:
    static double rate() { return interestRate; }
    static void rate(double);   
private:
    std::string owner; 
    double amount = 0.0;
    static double interestRate; 
    static double initRate() { return .0225; }
    static const std::string accountType;
    static constexpr int period = 30;// period is a constant expression
    double daily_tbl[period];
};
#endif
//Account.cc
#include <string>
using std::string;

#include "Account.h"

// define static data and function members
const string Account::accountType("Savings Account");
double Account::interestRate = initRate();

void Account::rate(double newRate) 
{
    interestRate = newRate; 
}
// useAccount.cc
#include <iostream>
using std::cout; using std::endl;

#include <string>
using std::string;

#include "Account.h"

int main()
{
	Account a1("bem", 42);
	cout << a1.balance() << endl;
	a1.calculate();
	cout << a1.balance() << endl;

	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章