为什么这不起作用?我正在尝试为 int+Date 定义 + 运算符并使其返回一个 int。所以我将operator+定义为一个成员来定义Date+int,我定义了一个非成员函数operator+(int, Date),但是在main中使用的时候好像没有使用那个函数并产生错误
class Date
{ int D;
int M;
int Y;
public:
Date();
Date(int, int, int);
~Date(void);
int getDay() const;
Date operator+(Date) const;
Date operator+(int) const;
};
Date::Date()
{
D = 15;
Y = 2012;
M = 2;
}
Date::Date(int d, int m, int y)
{
D = d;
Y = y;
M = m;
}
Date::~Date(void)
{
}
int Date::getDay() const
{
return D;
}
Date Date::operator+(Date d) const
{
return Date(d.D+D,d.M+M,d.Y+Y);
}
Date Date::operator+(int d) const
{
return Date(d+D,M,Y);
}
int operator+(int i,Date d) // This is what is wrong apparently.
{
return i + d.getDay();
}
int main ()
{
Date d = Date();
int i = 7 + d; // This is what generates the error at compile time.
cout << i;
return 0;
}