Question

I usually keep my classes in 2 files : class.h and class.cpp

I want to do something like cout << myclass;

I have found examples like :

friend ostream& operator<<(ostream &os, XXLint)
{ // do stuff
}

But the above function gets explicited right after the declaration.

How should I declare it in myclass.h in order to be able to use it in myclass.cpp ? And also what would the entire function's header be in the .cpp file ( eg : myclass::myclass() ).

Was it helpful?

Solution

In the class definition in the header:

struct Foo
{
  int a, b;
  friend std::ostream& operator<<(std::ostream &os, const Foo&);
};

In an implementation (e.g. .cpp file):

std::ostream& operator<<(std::ostream &os, const Foo& f)
{
  return os << f.a << " " << f.b;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top