简体   繁体   中英

Operator Overloading c++ adding int to object

I'm just getting started with operator overloading and trying to understand the concept. So I want to overload the operator +. In my header file I have

   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;

So basically in my main I created an Object from upDate and I want to add it to an int.

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

How would I go in writing the overload so it would add 5 days to D2? I have this but I'm pretty sure the syntax is incorrect and an error appears still. Any help would be appreciated

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

  {

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

You will need to define another overload of operator+ that takes an int as argument:

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

Edit: as Dolphiniac has noted, you should define a copy constructor to initialize temp correctly.

Make a copy constructor to actually make a copy of this . Your function is returning an object with fields missing that would normally be in this instance.

Overload the compound plus operator instead.

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

and you can do something like

D2 += 5;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM