第21章 C++版カレンダー


クラスは、もう飽きた!という人のために、 C言語編第41章で 作ったカレンダー(というか、日付を入れると曜日が求まるもの) をC++風に作り替えてみましょう。

#include <iostream.h> #include <stdlib.h> #include <string.h> #define FL(x) ((int)(x) > (x) ? (int)(x) - 1 : (int)(x)) class date { int year; int month; int day; public: date(int a, int b, int c); int calc_date(); }; //引数付きコンストラクタ date::date(int a, int b, int c) { year = a; month = b; day = c; } //曜日の計算 int date::calc_date(void) { int yobi; if (month <= 2) { month += 12; year -= 1; } yobi = (year + FL(year / 4) - FL(year / 100) + FL(year / 400) + FL(2.6 * month + 1.6) + day) % 7; return yobi; } int main(void) { char str[32], nen[5], gatsu[3], nichi[3]; int yobi; static char *day_of_week[7] = {"日", "月", "火", "水", "木", "金", "土"}; cout << "E入力で終了" << endl; while (1) { cout << "日付(yy/mm/dd)==>"; cin >> str; if (strcmp(str, "E") == 0) break; nen[0] = '1'; nen[1] = '9'; nen[2] = str[0]; nen[3] = str[1]; nen[4] = '\0'; gatsu[0] = str[3]; gatsu[1] = str[4]; gatsu[2] = '\0'; nichi[0] = str[6]; nichi[1] = str[7]; nichi[2] = '\0'; date A(atoi(nen), atoi(gatsu), atoi(nichi)); yobi = A.calc_date(); cout << day_of_week[yobi] << "曜日" << endl; } return 0; }


dateクラスは、いろいろな入門書によく出てきます。
データメンバとして年、月、日をint型の整数として持っています。 コンストラクタで、これらのデータメンバに、値を代入しています。 メンバ関数のcalc_dateは、データメンバをもとに、その曜日を int型整数で返します。データメンバには、必ず数値が入っています。 (コンストラクタで代入しているので)しかし、その数値が 意味のないものである可能性があります。これをチェックする 機能をdateクラスに持たせてみて下さい。


[C++Index] [総合Index] [Previous Chapter] [Next Chapter]

Update Jan/31/1997 By Y.Kumei
当ホーム・ページの一部または全部を無断で複写、複製、 転載あるいはコンピュータ等のファイルに保存することを禁じます。