スニペットを修正する最も簡潔な方法は、 Date
オブジェクトの出力演算子を提供することです。
std::ostream& operator << (std::ostream& os, const Date& date)
{
return os << date.day << "/" << date.month << "/" << date.year;
}
その後、正しい入力を使ってユーザー入力を読みます。
cin >> d >> m >> y;
そして最後に、コンパイラによって生成された Date
コンストラクタを使用します。
cout << Date{d, m, y};
入力を検証しない限り、日付オブジェクトを作成する関数は必要ありません。
Note, however, that Date
objects can now be in
invalid states (negative day or month values etc.), so for future
refinement, you should either implement a proper constructor that
throws upon illegal input, or change the createDate
function such that it e.g. returns a std::optional
which is empty (std::nullopt
) upon illegal input.