如何重载operator +

时间:2013-05-08 22:54:11

标签: c++ overloading operator-keyword

所以我想重载operator+。这是我到目前为止所做的,但它仍然没有用。我将如何编写语法? 头文件:

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

我的.cpp文件

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

我的主要是

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

错误是我无法将对象添加到int。我已经尝试了它的工作方式,但它只适用于D3 = D2 + 5而不是D4。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

您需要两个功能:

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

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

答案 1 :(得分:0)

你需要:

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

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

或者你可以让一个构造函数接受一个int并让转换为你工作....但是这有点奇怪,因为你要添加一个持续时间,而你的类代表一个日期。但是你的实际操作员+无论如何都有这个问题 - 添加2个日期意味着什么?

编辑:看一下c ++ 11中的chrono,它可以很好地区分 时间点 时间

答案 2 :(得分:0)

为了最大限度地减少编码冗余,以下是人们通常如何实现各种相关操作:

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