操作符重载c++在对象中添加int

Operator Overloading c++ adding int to object

本文关键字:添加 int 对象 重载 c++ 操作符      更新时间:2023-10-16

我刚刚开始学习操作符重载,并试图理解这个概念。我想重载运算符+。在头文件中有

   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;

在我的main中,我创建了一个upDate对象我想把它添加到int类型

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

我该如何写过载,使D2增加5天?我有这个,但我很确定语法是不正确的,错误仍然出现。如有任何帮助,不胜感激

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

您需要定义另一个以int型作为实参的操作符+重载:

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

编辑:正如Dolphiniac所指出的,你应该定义一个复制构造函数来正确初始化temp

创建一个复制构造函数来实际复制this。您的函数正在返回一个对象,该对象通常在this实例中缺少字段。

重载compound plus操作符

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

D2 += 5;