3

I have the following code to overload the + and += operators respectively for the class Date. The operator + was successfully overloaded, and it will take an integer n and increase Date objects by n days. This is done by applying the next_day function n times.

inline Date operator+(Date d, int n)
{
    for(char j=1; j<=n; j++){
        d=d.next_day(d);
    }
    return d;
}
inline Date operator+=(Date d, int n)
{
    Date p=d+n;
    return p;
}

Having overloaded the + operator, I'm using it to define the overloading of += as well. But although no errors occurred in compilation, when I use the overloaded += it doesn't seem to have any effect.

Here's my main.cpp:

#include <iostream>
#include "Date.h"
using namespace std;

int main() {

Date Initialday = Date (12,1,2012);

Initialday+=1;
cout <<"Next day = "<< Initialday <<endl;

return 0;
}

Running the main function still gives me 12/1/2012 instead of 12/2/2012. What am I doing wrong? Note: I've already overloaded << to output Date objects in a readable format, so I don't think that's the issue.

4

2 回答 2

5

简单的解决方法是通过引用获取您的 Date 对象,对其进行修改,然后通过引用返回它。这是 的预期行为operator+=

inline Date& operator+=(Date &d, int n)
{
    d = d + n;
    return d;
}

但是,在实施operator+=方面operator+是倒退的。应该反过来。 operator+=应该作用于对象的成员,直接改变它们。那么operator+应该按照以下方式实施:

inline Date& operator+=(Date& lhs, int rhs)
{
    ... // code here to modify lhs directly

    return lhs;
}

inline Date operator+(Date lhs, int rhs)
{
    return lhs += rhs;
}
于 2013-02-17T07:24:20.957 回答
2

主要问题是您+=正在创建一个新的 Date 对象并返回它。那是错误的语义,而且您没有将该返回值分配给任何东西。操作员应该作用于它所应用的+=实例并通过引用返回它:

inline Date& operator+=(Date& d, int n) {
   return d = d + n;
}

通常,这将作为成员函数+实现,并按照以下方式实现+=

class Date
{
 public:
    Date& operator+=(int n) {
       // perform whatever operation is required using
       // the state of the instance.
       return *this;
    }
};

inline Date operator+(Date lhs, int rhs) {
  return lhs += rhs; // calls member +=
}

最简洁的方法是提供一个持续时间类,并根据 aDate和 a实现所有运算符TimeDuration

struct TimeDuration { .... };

class Date
{
 public:
  Date& operator+= (const TimeDuration& rhs) { .... }
};
inline Date operator+(Date lhs, const TimeDuration& rhs) { return lhs += rhs; }
于 2013-02-17T07:24:54.027 回答