0

I'm trying to define the + operator for int + Date and make it return an int. So I define operator+ as a member to define Date + int, and I define a non-member function operator+(int, Date), but when using it in the main it doesn't seem to use that function and generates an error.

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;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
reverse_engineer
  • 4,239
  • 4
  • 18
  • 27
  • 2
    It compiles and runs ok for me: http://ideone.com/8Jbt8. – Oliver Charlesworth Feb 29 '12 at 22:36
  • OK I'm very stupid apparently, my bad. In my code the Date class was in a separate file, and I forgot to include the operator+ function in the header file... Here there was no problem because it was defined in the same code... Thanks for the reactions guys! – reverse_engineer Mar 03 '12 at 08:11

1 Answers1

2

You can define it as a friendly function outside the class.

Please consider the link with an example:

http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/

Dmitriy Kachko
  • 2,804
  • 1
  • 19
  • 21