我的 if 语句逻辑有问题


#include <iostream>
using namespace std;
class Date {
private:
int day, month, year;
public:
Date(int, int, int);
Date();
friend istream& operator >> (istream&, Date&);
friend ostream& operator << (ostream&, const Date&);
friend bool operator !=(const Date&, const Date&);
friend bool operator ==(const Date&, const Date&);
friend bool operator <(const Date&, const Date&);
};
Date::Date(int d, int m, int y) {
month = m;
day = d;
year = y;
}
Date::Date() {
day = 0;
month = 0;
year = 0;
}
istream& operator >> (istream& dates, Date& t) {
cin >> t.day;
cout << "Day: " << t.day << endl;
cin >> t.month;
cout << "Month: " << t.month << endl;
cin >> t.year;
cout << "Year: " << t.year << endl;
cout << endl;
return dates;
}
ostream& operator << (ostream& dates, const Date& t) {
dates << t.day << "/" << t.month << "/" << t.year << endl;
return dates;
}
bool operator <(const Date& date, const Date& dat) {
return (date.year < dat.year);
return (date.month < dat.month);
return (date.day < dat.day);
}
bool operator == (const Date& date, const Date& dat) {
return (date.year == dat.year);
}
bool operator !=(const Date& date, const Date& dat) {
return (date.year != dat.year);
return (date.month != dat.month);
return (date.day != dat.day);
}


int main()
{
Date dates(0, 0, 0);
Date dates2(0, 0, 0);

cout << "Please enter a date: " << endl;
cin >> dates;
cout << "Your date is: " << dates;

cout << endl;
cout << "Please enter a date: " << endl;
cin >> dates2;
cout << "Your date is: " << dates2;
cout << endl;
if (dates != dates2) {
cout << "Your date is not the same " << endl;
}
else {
cout << "Your date is the same " << endl;
}
cout << endl;
if (dates < dates2) {
cout << "Person 2 is older ";
}
else if (dates == dates2) {
cout << "They we're born on the same date. ";
}
else {
cout << "Person 1 is younger ";
}
return 0;
}

我目前的if语句逻辑有问题,当我为我的第一次约会输入2001年11月26日和2001年11日23日之类的信息时,它会说这是同一天,而且我们出生在同一天。我的目标是让我的if语句通过年月日,并检查它们是否相同,如果所有这些都相同,那么它应该输出,";你和我们出生在同一天"以及";这是同一天"但现在,只有当其中一个变量匹配时,它才会打印出这两行代码。

bool operator <(const Date& date, const Date& dat) {
return (date.year < dat.year);
return (date.month < dat.month);
return (date.day < dat.day);
}

只有第一个return被使用过,其他两个都是死代码。

这里你需要做的是让退货有条件,就像这样:

bool operator <(const Date& date, const Date& dat) {
if (date.year == dat.year) {
if (date.month == dat.month) {
return date.day < dat.day;
}
return date.month < dat.month;
}
return date.year < dat.year;
}

看起来操作符==代码只比较年份,如果年份匹配则返回true。

bool operator == (const Date& date, const Date& dat) {
return (date.year == dat.year);
}

试试这个:

return ((date.month == dat.month) && (date.day == dat.day) && (date.year == 
dat.year));

最新更新