How to overload operator+

梦想的初衷 提交于 2021-02-05 09:04:27

问题


So I want to overload operator+. Here is what I have so far, but it's still not working. How would I go in writing the syntax? Header file:

private:
        int month;
        int year;
        int day;

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(); 
    friend upDate operator+(const upDate &lhs, const upDate &rhs);

My .cpp file

    upDate::upDate()
{
    month = 12;
    day = 12;
    year = 1999;
}
upDate::upDate(int M, int D, int Y)
{
    month = M;
    day = D;
    year = Y;
}//end constructor
void upDate::setDate(int M, int D, int Y)
{
    month = M;
    day = D;
    year = Y;
}//end setDate
int upDate::getMonth()
{
    return month;
}//end get Month
int upDate::getDay()
{
    return day;
}//end getDate
int upDate::getYear()
{
    return year;
}//end getYear

upDate operator+(const upDate &lhs, const upDate &rhs)

{
upDate temp;
temp.day = lhs.day + rhs.day; 
return (temp); 
}

In my main I have

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

The error is that I can't add an object to an int. I've tried ways in which it worked, but it only worked for the D3 = D2 + 5 and not the D4. Any help would be appreciated.


回答1:


You need two functions:

upDate operator+(int days, const upDate &rhs)
{
   ... add days to date ... 
}

and

upDate operator+(const upDate &lhs, int days)
{
   ...
}



回答2:


You need:

upDate operator+(const upDate &lhs, int days)
{
    ...
}

upDate operator+(int days, const upDate &rhs)
{
    ....
}

Alternatively you could have a constructor taking a single int and let the conversions work for you.... but this is a little weird as you're adding a duration whereas your class represents a date. But your actual operator+ has this problem anyway - what does it mean to add 2 dates?

EDIT: Take a look at chrono in c++11, it makes a good distinction between points in time and durations of time




回答3:


To minimize coding redundancy, here's how one would usually implement various related operations:

struct Date
{
    Date & operator+=(int n)
    {
        // heavy lifting logic to "add n days"
        return *this;
    }

    Date operator+(int n) const
    {
        Date d(*this);
        d += n;
        return d;
    }

    // ...
};

Date operator(int n, Date const & rhs)
{ 
    return rhs + n;
}       


来源:https://stackoverflow.com/questions/16451561/how-to-overload-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!