Created
September 19, 2011 07:55
-
-
Save torazuka/1226127 to your computer and use it in GitHub Desktop.
Chapter09_drill02_PPPC++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
『ストラウストラップのプログラミング入門』 | |
9章ドリル2(9.4.2バージョン, メンバ関数を持つstruct) | |
*/ | |
#include "../../std_lib_facilities.h" | |
struct Date{ | |
int y, m, d; // 年月日 | |
Date(int y, int m, int d); // 日付の有効性を確認して初期化する | |
void add_year(int n); | |
void add_month(int n); | |
void add_day(int n); | |
void init_day(int y, int m, int d); | |
}; | |
Date::Date(int y, int m, int d) | |
{ | |
init_day(y, m, d); | |
} | |
bool leapyear(int y) | |
// うるう年ならtrueを返す | |
{ | |
bool result = false; | |
if(y % 4 == 0 && y % 100 != 0){ | |
result = true; | |
} | |
if(y % 400 == 0){ | |
result = true; | |
} | |
return result; | |
} | |
int get_days_in_month(int y, int m) | |
// その月の日数を返す | |
{ | |
int result = 31; | |
switch(m){ | |
case 2: | |
result = (leapyear(y)) ? 29 : 28; | |
break; | |
case 4: case 6: case 9: case 11: | |
result = 30; | |
break; | |
} | |
return result; | |
} | |
void Date::init_day(int yy, int mm, int dd) | |
// (yy, mm, dd)が有効な日付かどうかを確認する | |
// そうである場合はddを初期化する | |
{ | |
if(yy < 1){ | |
error("bad year"); | |
} | |
if(mm < 1 || 12 < mm){ | |
error("bad month"); | |
} | |
if(dd < 1){ | |
error("bad day"); | |
} | |
if(get_days_in_month(yy, mm) < dd){ | |
error("over day"); | |
} | |
y = yy; | |
m = mm; | |
d = dd; | |
} | |
void Date::add_year(int n) | |
{ | |
y += n; | |
} | |
void Date::add_month(int n) | |
{ | |
const int months_in_year = 12; | |
// 月数nを現在の月に足すと、12を超える場合、翌年に繰り越す | |
if(months_in_year < (m + n)){ | |
add_year(1); | |
add_month(n - months_in_year); | |
} else { | |
m += n; | |
} | |
} | |
void Date::add_day(int n) | |
{ | |
int days_in_month = get_days_in_month(y, m); | |
// 日数nを現在の日に足すと、当月内の日数を超える場合、翌月に繰り越す | |
if(days_in_month < (d + n)){ | |
add_month(1); | |
add_day(n - days_in_month); | |
} else { | |
d += n; | |
} | |
} | |
ostream& operator<<(ostream& os, const Date dd) | |
{ | |
return os << '(' << dd.y | |
<< ',' << dd.m | |
<< ',' << dd.d << ')'; | |
} | |
void f() | |
{ | |
Date today(1978, 6, 25); | |
Date tomorrow(today.y, today.m, today.d); | |
tomorrow.add_day(1); | |
cout << today << '\n' << tomorrow << endl; | |
} | |
int main() | |
{ | |
f(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment