Header file ostream/istream problems

Trying to compile and link a few files; stuff from Stroustrup's Programming, Principles and Practice regarding the Date class

In the header file I have the following declarations:

1
2
ostream& operator<<(ostream& os, const Date& d);
istream& operator>>(istream& is, Date& dd);


and their definitions in the relevant .cpp file.

However, I get the error message (regarding both lines) that says
expected constructor, destructor or type converion before '&' token

What are the culprits?
Do you have iostream included?
Yes but it still displays the same error message
Have Date been declared before these two lines?
Yes, declared with all its member functions and defined in .cpp file
I think the culptrit is that iostream is not included in your Date.cpp file, but more information would be needed for me to say otherwise.

I tried doing this to see if it worked:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

class Date
{
   std::ostream& operator<<(std::ostream& os, const Date& d);
   std::istream& operator>>(std::istream& is, Date& dd);
};

int main()
{
   return 0;
}


g++ gave me this error:
code.cpp:5:60: error: 'std::ostream& Date::operator<<(std::ostream&, const Date&)' must take exactly one argument
code.cpp:6:55: error: 'std::istream& Date::operator>>(std::istream&, Date&)' must take exactly one argument


So I tried this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

class Date
{
   std::ostream& operator<<(const Date& d);
   std::istream& operator>>(Date& dd);
};

int main()
{
   return 0;
}


It compiled.
You are using it as a member function
1
2
Date today, yesterday = today-1;
today << yesterday; //¿eh? 


std::ostream& operator<<(std::ostream& os, const Date& d); is for a global function (that you may declare as friend of your class)
std::cout << today;
Yeah thanks ne555
Maybe Amnesiac will figure out the solution now?
I was just trying to give him something that worked. Could you take a look at the actual question since you fixed mine?

Peter probably has the correct solution though.
Last edited on
Topic archived. No new replies allowed.