2013-05-08 41 views
1

我剛剛開始使用運算符重載並試圖理解該概念。所以我想重載operator +。在我的頭文件我有運算符重載C++將int添加到對象

public: 
    upDate(); 
    upDate(int M, int D, int Y); 
    void setDate(int M, int D, int Y); 
    int getMonth(); 
    int getDay(); 
    int getYear(); 
    int getDateCount(); 
    string getMonthName(); 
    upDate operator+(const upDate& rhs)const; 

    private: 
     int month; 
     int year; 
     int day; 

所以基本上在我的主,我創建的更新一個對象,我想將它添加到一個int。

upDate D1(10,10,2010);//CONSTRUCTOR 
    upDate D2(D1);//copy constructor 
    upDate D3 = D2 + 5;//add 5 days to D2 

我該如何去寫超負荷,所以會增加5天到D2?我有這個,但我敢肯定,語法是不正確的,仍然出現錯誤。任何幫助,將不勝感激

upDate upDate::operator+(const upDate& rhs)const 

    { 

    upDate temp; 
    temp.day = this->day+ rhs.day; 
    return temp; 
} 

回答

3

您需要定義operator +的另一個重載接受一個int作爲參數:

upDate upDate::operator+(int days) const{  
    upDate temp(*this); 
    temp.day += days; 
    return temp; 
} 

編輯:作爲Dolphiniac所指出的,你應該定義一個拷貝構造函數初始化temp正確。

+0

我不知道這是否是相關的,但如果我是用朋友的頭文件運算符重載那會是更有幫助 – 2013-05-08 20:38:54

+0

讓這個超載的朋友不會改變任何東西,因爲這個超載是一個成員函數(例如它已經可以訪問私有字段)。 – 2013-05-08 20:41:26

+0

哦,好的,謝謝。是否可以爲+寫兩個Operation Overload?例如在我的主要我也有D4 = 5 + D2,這是一個int + upDate – 2013-05-08 20:51:27

3

製作複製構造函數以實際製作this的副本。您的函數正在返回一個對象,其中缺少的字段通常位於this實例中。

0

改爲重載compound plus運營商。

upDate& upDate::operator+=(const int& rhs) 
{ 
    this->day += rhs; 
    return *this; 
} 

,你可以這樣做

D2 += 5;