Domanda

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() ).

È stato utile?

Soluzione

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top