如何重载operator + [英] How to overload operator+

查看:55
本文介绍了如何重载operator +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想重载 operator + .这是我到目前为止的内容,但仍然无法正常工作.我将如何编写语法?头文件:

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

我的.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.任何帮助将不胜感激.

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.

推荐答案

您需要两个函数:

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

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

这篇关于如何重载operator +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆