I have this question in assignment.
Question: Implement + and - operators for the Date class where u give dates using constructor and also give and additional n value. Now we have to use operator + and operator - to change the previously taken date by n value.
I have done this and it given an error: operator+(Date&, int) must take either zero or one argument
class Date
{
int day;
int month;
int year;
public:
Date(int d,int m,int y)
{
day=d;
month=m;
year=y;
}
Date operator-(Date &x,int y)
{
return Date(x.day-y, x.month, x.year);
}
Date operator+(Date &x,int y)
{
return Date(x.day+y, x.month, x.year);
}
void display()
{
cout<<"Date:"<<day<<"-"<<month<<"-"<<year<<endl;
}
};
After i searched in web and found this:
class Date{
private:
int day;
int mth;
int year;
public:
Date(int a,int b,int c){
day = a;
mth = b;
year = c;
}
friend Date operator +(Date &,int);
friend Date operator -(Date &,int);
void print(void){
cout <<"Date: " << day << " - " << mth << " - " << year << endl;
}
};
Date operator +(Date& a,int n){
Date d(a.day+n,a.mth,a.year);
return(d);
}
Date operator -(Date& a,int n){
Date d(a.day-n,a.mth,a.year);
return(d);
}
My Doubt: Both are same but he used friend function and it got solved. In both cases the operator overloading function is same and error is also pointing towards the function. How this friend function solved the issue or anything wrong in my Operator overload function?
Aucun commentaire:
Enregistrer un commentaire