Reputation: 61
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;
}
Upvotes: 1
Views: 6294
Reputation: 5998
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;
Upvotes: 1
Reputation: 1802
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.
Upvotes: 3
Reputation: 17026
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.
Upvotes: 4