前提・実現したいこと
現在、C++でオペレーターのオーバーロードの仕方を学んでおります、
ある日付からある日付の経過日数をアウトプットしようといております。
下記のコードの場合、Date date1(10,16,2000); と Date date2(12,24,2004); の間の日数を得たいです。
1年は360日、毎月変わらず30日としています。
main関数内でdate1とdate2どちらの方が昔かを確かめて、date1とdate2の間の日数を求めようとしています。
bool operator < (const Date& d) {
if (year < d.year) {
return true;
}
if (year == d.year && month < d.month) {
return true;
}
if (year == d.year && month == d.month && day < d.day) {
return true;
}
return false;
}
上記のコードと下記のコードをどの様にMain関数に渡すのか教えて頂きたいです。
また、day = (day * 30) - (day * 30); この部分はこれであっていますでしょうか?
少しこれで良いのかどうか自信がないので確認したいです。
よろしくお願いいたします。
int operator -(const Date& d) {
month = (month * 12) - (month * 12);
day = (day * 30) - (day * 30);
year = (year * 360) - (year * 360);
return month + day + year; }
C++
#include <iostream> #include <string> using namespace std; class Date { private: int month; int day; int year; public: Date () { month = 0; day = 0; year = 0; } Date (int m, int d, int y) { month = m; day = d; year = y; } int getMonth() { return month; } void setMonth(int m) { month = m; } int getDay() { return day; } void setDay(int d) { day = d; } int getYear() { return year; } void setYear(int y) { year = y; } bool operator < (const Date& d) { if (year < d.year) { return true; } if (year == d.year && month < d.month) { return true; } if (year == d.year && month == d.month && day < d.day) { return true; } return false; } int operator -(const Date& d) { month = (month * 12) - (month * 12); day = (day * 30) - (day * 30); year = (year * 360) - (year * 360); return month + day + year; } // void display() { // // cout << month << day << year << date1 // } }; int main() { Date date1(10,16,2000); Date date2(12,24,2004); int date3; Date D1(date1), D2(date2); if( D1 < D2 ) { cout << date1.getMonth() << date1.getDay() << date1.getYear() << " is earlier than " << date2.getMonth() << date2.getDay() << date2.getYear() << endl; date3 = date2 - date1; cout << "The number of days between the dates is " << date3 << endl; } else { cout << date1.getMonth() << date1.getDay() << date1.getYear() << " is later than " << date2.getMonth() << date2.getDay() << date2.getYear() << endl; date3 = date1 - date2; cout << "The number of days between the dates is " << date3 << endl; } return 0; }
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/18 04:27