2013-02-17 149 views
1

我有以下代碼分別爲類Date的+和+ =運算符重載。運算符+已成功重載,並且它將採用整數n並將Date對象增加n天。這是通過將next_day函數應用n次來完成的。重載+ =運算符

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; 
} 

在重載+運算符後,我使用它來定義+ =的重載。但是,雖然在編譯過程中沒有發生錯誤,但是當我使用重載的+ =時,它似乎沒有任何影響。

這裏是我的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; 
} 

運行的主要功能仍然給我2012年12月1日,而不是2012年12月2日。我究竟做錯了什麼?注意:我已經超載了< <以可讀格式輸出Date對象,所以我不認爲這是問題所在。

回答

3

簡單的修復方法是通過引用來獲取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; 
} 
+0

非常感謝!我同意,它有些倒退 - 但在這種情況下,+ =和+似乎同樣簡單,因爲我已經定義了next_day函數,並且認爲我可以使用它。我想作爲一個初學者,我首先定義+看起來更直觀! – 2013-02-17 07:45:35

+0

只是爲了學習,請問爲什麼以下不行? 'inline Date&operator + =(Date&d,int n) { Date p = d + n; return p; }' 它給了我一個錯誤消息,說本地變量p被自動返回。這是什麼意思? – 2013-02-17 07:45:58

+0

@PatrickJane:這個問題並不是真的那麼簡單,比另一個更直接。這個問題主要是表現。 'operator +'接受兩個對象,並從它們中創建一個完全獨立的對象。但是沒有理由'operator + ='應該需要構造一個新的對象。通過以'operator +'的形式實現'operator + =',您可以複製對象,修改副本,然後將副本複製回原始對象。這是兩個不必要的副本,當它需要做的只是修改原始對象。 – 2013-02-17 07:53:23

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 += 
} 

最簡潔的方法是提供一個持續時間等級,並按照DateTimeDuration執行所有運營商:

struct TimeDuration { .... }; 

class Date 
{ 
public: 
    Date& operator+= (const TimeDuration& rhs) { .... } 
}; 
inline Date operator+(Date lhs, const TimeDuration& rhs) { return lhs += rhs; } 
+0

究竟是什麼意思將兩個日期相互添加? – 2013-02-17 07:38:24

+0

@BenjaminLindley這意味着我還沒有喝咖啡。需要的是時差類型,但我想我會刪除這個無用的答案。 – juanchopanza 2013-02-17 07:42:43

+0

@BenjaminLindley該死的,它已被接受,所以我現在必須修復它... – juanchopanza 2013-02-17 07:43:36