我写了一个 Date 类,我正在尝试在这个类上练习运算符重载。我试图重载 operator++
以将一天递增,但我仍然收到此错误:无法递增“日期”类型的值!
这是我重载此运算符的方法:
Date Date::operator++()
{
day++;
if (day > days_of_month(month, year)) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
return *this;
}
这是 days_of_month
方法:
int days_of_month(int m, int y)
{
if (m < 7)
return 31;
else if (m < 12)
return 30;
else if (m == 12)
return is_leap_year(y) ? 30 : 29;
else
abort();
}
最佳答案
递增有两种类型——后递增和预递增。您重载的是后者,而您正在尝试使用前者。
通常你会为一个类提供这两个。它看起来像这样:
Date& Date::operator++() // for ++d
Date Date::operator++(int) // for d++
关于c++ - 试图为我的日期类重载 operator++。仍然收到错误 : cannot increment value of type 'Date' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50233463/