Search code examples
c++structoperator-overloadingstructure

Overloading operators with structures in c++


So I am doing a simple, (or so I thought) exercise to help build my C++ skills.

I have this simple struct to keep track of date information. I need to overload an operator to display the results. This is a simple function that I have used before in classes, and never had any problems with. However, in this exercise I am getting the following error:

Expression preceding parentheses of apparent call must have (pointer-to-) function type

Here is my code. The problem function is the ostream& operator << (ostream& os, const Date date) function and is commented in the code.

    #include<iostream>
    #include<ostream>
    #include "error.h"

    using namespace std;

    inline void keep_window_open(string s)
    {
        if (s == "") return;
        cin.clear();
        cin.ignore(120, '\n');
        for (;;) {
            cout << "Please enter " << s << " to exit\n";
            string ss;
            while (cin >> ss && ss != s)
                cout << "Please enter " << s << " to exit\n";
            return;
        }
    }
        struct Date {   
            int year;
            int month;
            int day;
        };
        Date today;
        Date tomorrow;

        // Helper functions
        void initializeDay(Date& date, int year, int month, int day)
        {
            if (month < 1 || month > 12)
            {
                error("Invalid month");
            }
            if (day < 1 || day > 31)
            {
                error("Invalid day");
            }
            date.year = year;
            date.month = month;
            date.day = day;
        }

        void addDay(Date& date, int daysToAdd)
        {
            date.day += daysToAdd;
        }       

        // Does not work    
        ostream& operator << (ostream& os, const Date date)
        {
            return os << '(' << date.year()
                << ',' << date.month()
                << ',' << date.day()
                << ')';
        }

    int main()
    {           
        initializeDay(today, 2020, 9, 21);  
        tomorrow = today;
        addDay(tomorrow, 1);

        keep_window_open("~");

        return 0;
    }

Like I said I have used the problem function before without problem. The only thing I can think of is it is has something to do with the struct, but that doesn't make sense to me. So I am thinking it maybe something else.

Any help would be greatly appreciated. Thank you for your time and your help.


Solution

  • Your structure does not implement any method. Instead of calling date.year() simply call date.year