#include #include using namespace std; // ノートクラス. class Notebook { protected: string* note; // ノートの本文. int pages; // ノートの総ページ数. public: // ノートクラスのコンストラクタ Notebook() { pages = 0; note = NULL; } Notebook(int pp) { note = new string[pages=pp]; } // ノートクラスのデストラクタ 用意したノートを削除. virtual ~Notebook() { delete [] note; } // ノートを読む 指定がなければ最初のページ(1ページ目)を読む. virtual string Read(int p = 1) const; // ノートに書く 指定がなければ最初のページ(1ページ目)に書く. virtual void Write(string, int p = 1); }; // ノートを読む. string Notebook::Read(int p) const { p--; // ノートは1ページ目が最初のページ. if (p >= 0 && p < pages) { if (note[p].empty()) return "This page is empty."; return note[p]; // noteの内容を返す. } else return "Cannot read: out of pages."; // ページ外. } // ノートに書く. void Notebook::Write(string str, int p) { p--; // ノートは1ページ目が最初のページ. if (p >= 0 && p < pages) note[p] = str; // noteに代入する. else cerr << "Cannot write: out of pages." << endl; // ページ外. } // 日記クラス. class Diary : public Notebook { public: // 日記クラスのコンストラクタ 1年は365日とする. Diary() { note = new string[pages=365]; } virtual ~Diary() { } // 指定した日付を元日からの日数に変換. int DateToPage(int, int) const; // 指定したページの日記を読む. string Read(int) const; // 指定した日付の日記を読む. string Read(int, int) const; // 指定したページに日記を書く. void Write(string, int); // 指定した日付の日記を書く. void Write(int, int, string); }; // 月の日数. static const int days_of_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // 指定した日付を元旦からの日数に変換. int Diary::DateToPage(int m, int d) const { // 正しい日付か判定. if (m < 1 || m > 12 || d < 1 || d > days_of_month[m-1]) { cerr << "Error of date: " << m << "/" << d << endl; return -1; } // 日数を計算. int days = 0; for (int i = 0; i < m - 1; i++) days += days_of_month[i]; return days + d; } // 指定したページの日記を読む. string Diary::Read(int p) const { return Notebook::Read(p); } // 指定した日付の日記を読む. string Diary::Read(int m, int d) const { return Read(DateToPage(m, d)); } // 指定したページに日記を書く. void Diary::Write(string str, int p) { Notebook::Write(str, p); } // 指定した日付の日記を書く. void Diary::Write(int m, int d, string str) { Write(str, DateToPage(m, d)); } int main() { // 日記クラスのオブジェクト. Diary diary; // 日記を書く. diary.Write(5, 5, "Today is the holiday."); // 5月5日. diary.Write(7, 10, "Today is my birthday :D"); // 7月10日. diary.Write("This page is 3.", 3); // 3ページ目つまり1月3日. // 日記を読む. cout << diary.Read(1, 3) << endl; // 1月3日. cout << diary.Read(125) << endl; // 125ページ目は5月5日. cout << diary.Read(7, 10) << endl; // 7月10日. cout << diary.Read(8, 31) << endl; // 8月31日...この日はまだ書いてない. cout << diary.Read(2, 31) << endl; // 2月31日...?! 2月31日は存在しないよ! return 0; }