问题描述
我在作业中有这个问题。
问题: 为 Date 类实现 + 和 - 运算符,其中您使用构造函数给出日期,并给出额外的 n 值。现在我们必须使用运算符 + 和运算符 - 将之前拍摄的日期更改为 n 值。
我已经这样做了,但它给出了一个错误:operator+(Date&,int) 必须采用零个或一个参数
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.year);
}
void display()
{
cout<<"Date:"<<day<<"-"<<month<<"-"<<year<<endl;
}
};
在我在网上搜索并找到这个之后:
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.year);
return(d);
}
我的疑问:两者都是一样的,但他使用了朋友功能,问题得到了解决。在这两种情况下,运算符重载函数是相同的,错误也指向函数。这个友元函数如何解决我的运算符重载函数中的问题或任何错误?
解决方法
-
在第一个代码片段中,运算符函数是成员函数,因此它们应该是
operator+(int)
而不是operator+(Date&,int)
,因为Date &
类型的第一个参数是隐式的。 -
在第二个代码片段中,运算符函数不是成员函数,因此您需要一个
friend
限定符来访问Date
的私有成员。