【发布时间】:2021-07-29 02:34:54
【问题描述】:
我在作业中有这个问题。
问题: 为 Date 类实现 + 和 - 运算符,您可以在其中使用构造函数给出日期,并给出额外的 n 值。现在我们必须使用 operator + 和 operator - 将之前拍摄的日期更改为 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.month, 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.mth,a.year);
return(d);
}
我的疑问:两者都是一样的,但是他使用了朋友功能并且它得到了解决。在这两种情况下,运算符重载函数都是相同的,并且错误也指向该函数。这个友元函数如何解决我的运算符重载函数中的问题或任何错误?
【问题讨论】:
标签: c++11 operator-overloading friend-function