c++ - 试图为我的日期类重载 operator++。仍然收到错误 : cannot increment value of type 'Date'

标签 c++ oop operator-overloading

我写了一个 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/

相关文章:

c++ - 显式直接#include 与非契约传递#include

C++将数据读入结构数组

c++ - 使用基于 boost::tuple 的 fscanf 构建正则表达式以读取文件

PHP 命名空间 : equivalent to C# using

c++ - 包装指针如何与右值引用一起使用?

c++ - unordered_map find() 和 operator []

java - 默认类名 - 代码味道?

java - 为什么要在 OOPS 中定义重载方法?

输入对象没有 const 的 C++ 重载 << 会产生错误,该错误随 const 对象一起消失

c++ - 重载 << 运算符 - 多个参数