writing to an ostream via operator<<()

Hello there, I'm trying to get run an example from a book similar this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

struct Date
{
    int y;
    int m;
    int d;

    std::ostream& operator<< (std::ostream& os, Date& d)
    {
	return os << '(' << d.d << ',' << d.m ', '<< d.y << ')';
    }
};

int main()
{
    Date d;
    d.y=2013; d.m=2; d.d=14;

    std::cout << d;
}


When i try to compile, I get this message:
example1.c++:9:56: error: ‘std::ostream& Date::operator<<(std::ostream&, Date&)’ must take exactly one argument

Unfortunately, the code of the operator function is not nearer explained but used in some examples, please help me run it.
The overload operator << for streams can not be a class member. Or it can be but in this case the left operand will be an object of the class. So declare this operator function as a stand alone function.
ok so you have it almost ok.

all you need to do is to take
std::ostream& operator<< (std::ostream& os, Date& d)
    {
	return os << '(' << d.d << ',' << d.m <<','<< d.y << ')';
    }

outside of struct and than on line eleven after d.m you are missing operator <<and than you need to put comma there without free space. it gives you some weird numbers.
Thanks for your help, now it compiles fine.
no roblem... glad to help.. :)
Topic archived. No new replies allowed.