これまでにC++のクラスとオブジェクトの基本を学び、日付クラスの一部を例として使用しました。この記事では、小さな日付クラスを実装します。
まず、VSで3つのファイルを作成します:
Test.cpp:日付クラスのテスト用ファイル
日常生活では、日付に対して整数日を加算または減算できます。例えば、2004年2月1日に3日を加えると、2004年2月4日になります。同様に減算も可能です。しかし、日付に対して乗算や除算を行うことは意味がないため、演算子のオーバーロードでは乗算と除算は必要ありません。
まず、ヘッダーファイルで実装する機能を見てみましょう:
#pragma once
#include <iostream>
#include <cassert>
using namespace std;
class Date
{
public:
Date(int year = 2004, int month = 2, int day = 2);
void Print();
Date(const Date& d);
~Date()
{
_year = 0;
_month = 0;
_day = 0;
}
int GetDaysInMonth(int year, int month)
{
assert(month > 0 && month < 13);
static int MonthDays[13] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
{
return 29;
}
return MonthDays[month];
}
bool IsValidDate();
bool operator==(const Date& d) const;
bool operator!=(const Date& d) const;
bool operator<(const Date& d) const;
bool operator<=(const Date& d) const;
bool operator>(const Date& d) const;
bool operator>=(const Date& d) const;
Date& operator=(const Date& d);
Date operator++();
Date operator--();
Date operator++(int);
Date operator--(int);
Date& operator+=(int days);
Date operator+(int days) const;
Date& operator-=(int days);
Date operator-(int days) const;
int operator-(const Date& d) const;
private:
int _year;
int _month;
int _day;
};
内容の大部分は日付の加算と減算操作であり、次に日付の大小関係の判断操作などです。
Dateのコンストラクタは簡単だと思います。ここでは直接コードを表示します:
Date::Date(int year, int month, int day)
: _year(year), _month(month), _day(day)
{
if (!IsValidDate())
{
cout << "無効な日付: " << _year << "/" << _month << "/" << _day << endl;
}
}
ここでは初期化リストを使用し、デフォルトパラメータを関数宣言時に指定しています。これがDateコンストラクタです。また、日付が有効かどうかをチェックする関数もあります。これも簡単なので、直接表示します:
bool Date::IsValidDate()
{
if (_month < 1 || _month > 12 || _day < 1 || _day > GetDaysInMonth(_year, _month))
{
return false;
}
return true;
}
次にコピーコンストラクタを見てみましょう。これも簡単です:
Date::Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
GetDaysInMonth関数については、C言語を学習した際に書いたことがあると思います。よく見れば理解できるはずです。主に演算子のオーバーロードについて説明します:
bool operator==(const Date& d) const;
bool operator!=(const Date& d) const;
bool operator<(const Date& d) const;
bool operator<=(const Date& d) const;
bool operator>(const Date& d) const;
bool operator>=(const Date& d) const;
これらの比較演算子について、実際には2つだけ書けば十分です。なぜなら、2つ書けば、他の比較演算子は基本的に再利用できるからです。例えば、