0

By the way, I am using eclipse and g++ on arch linux (I ran pacman -Syu less than a week ago, so everything is up to date).

Eclipse produces an error every time I try to compile this:

#ifndef DATE_HPP_
#define DATE_HPP_

using namespace std;

class Date {
public:
    int Year;
    char Month;
    char Day;
    char HH;
    char MM;
    char ss;
    Date();

    /*
     * Overloaded Operator Functions
     */
    //Assignments
    Date operator=(Date input);
    //Comparisons
    bool operator==(Date& rhs);
    bool operator!=(Date& rhs);
    bool operator<(Date& rhs);
    bool operator>(Date& rhs);
    bool operator<=(Date& rhs);
    bool operator>=(Date& rhs);
    //Conversion
    operator char*();
    operator std::string();
    ostream& operator<<(ostream& os, const Date& date); //TROUBLE LINE
};

#endif /* DATE_HPP_ */

Eclipse shows a message on the operator<< declaration saying it must only have a single argument. Yet, when I declare it like this:

ostream& operator<<(const Date& date);

It complains that it must have two. What am I doing wrong?

KG6ZVP
  • 3,610
  • 4
  • 26
  • 45

2 Answers2

4

The two-argument overload of the operator must be a non-member function. Either move it out of the class definition, or add friend to it to make it a non-member friend function, whichever makes more sense.

The one-argument overload is not useful, since it is used when the object instance is the left operand.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • So, would you recommend making it part of the header file? I didn't know there were two ways to overload the function. I've been googling for some good examples of << overloading, but I've yet to find anything that I could get to work. Do you have any links you could share? – KG6ZVP Oct 09 '13 at 01:46
  • @KG6ZVP: where you put the definition is up to you; only the declaration needs to be in the header. This is one of the most frequently asked questions, though, so I find it hard to believe you couldn't find *any* information. – Kerrek SB Oct 09 '13 at 08:25
  • The problem wasn't finding any information, it was finding lots of different threads that described doing things that made g++ freak out. I think I've got it sorted now. I left off teaching myself C++ before getting to overloaded operators and I'm pretty rusty on some of the basic syntax. – KG6ZVP Oct 09 '13 at 16:01
0

friend ostream& operator<<(ostream& os, const Date& date);

Also you can add some consts to your code. For example..

bool operator==(const Date& rhs) const;

I also suggest you make all integers int, even if they will only take a small value (such as month) unless there is a technical reason you need them to be chars.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91