C++11 搞不懂为什么用friend函数解决了这个问题
我在作业中有这个问题 问题: 为Date类实现+和-运算符,其中u使用构造函数给出日期,还提供和附加的n值。现在,我们必须使用运算符+和运算符-将以前的日期更改为n值 我这样做了,它给出了一个错误:运算符+(Date&,int)必须接受零或一个参数C++11 搞不懂为什么用friend函数解决了这个问题,c++11,operator-overloading,friend-function,C++11,Operator Overloading,Friend Function,我在作业中有这个问题 问题: 为Date类实现+和-运算符,其中u使用构造函数给出日期,还提供和附加的n值。现在,我们必须使用运算符+和运算符-将以前的日期更改为n值 我这样做了,它给出了一个错误:运算符+(Date&,int)必须接受零或一个参数 class Date { int day; int month; int year; public: Date(int d,int m,int y)
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;
}
};
上课日期
{
国际日;
整月;
国际年;
公众:
日期(整数d,整数m,整数y)
{
d=d;
月=m;
年份=y;
}
日期运算符-(日期和x,整数y)
{
返回日期(x.day-y,x.month,x.year);
}
日期运算符+(日期和x,整数y)
{
返回日期(x日+y、x月、x年);
}
无效显示()
{
库特
在第一个代码段中,运算符函数是成员函数,因此它们应该是operator+(int)
而不是operator+(Date&,int)
,因为Date&
类型的第一个参数是隐式的
在第二个代码段中,运算符函数不是成员函数,因此您需要一个friend
限定符来访问Date
的私有成员
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);
}