我正在尝试为int + Date
定义+
运算符,并使其成为return
和int
。因此,我将operator+
定义为定义Date + int
的成员,并定义了一个非成员函数operator+(int, Date)
,但当在主函数中使用它时,它似乎没有使用该函数,并产生错误。
class Date
{
int D, M, 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;
}
您可以将其定义为类外的友好函数。
请考虑带有示例的链接:
http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/