I am trying to overload the stream operator <<, for a class Foo which has already a toString() function returning a string, with the following code:
std::ostream &operator<<( std::ostream &flux, Foo const& foo )
{
flux << foo.toString();
return flux;
}
In order to use it in a main.cppfile
My question is: Where to put that piece of code?
- If I place it in the
main.cpp, before its usage, it works well, but i may want to use it in other files. -
If I place it in
foo.cpp, I get a ‘no such function’ error:src/main.cpp:77: error: no match for ‘operator<<’ in ‘std::cout << foo’which make sense since the code is not included to the
main.cppfile -
If I place it in the
foo.hclass header, outside class declaration, I get a ‘multiple definition’ error:foo.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Foo const&)': foo.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Matrix const&)' bar.o:bar.cpp:(.text+0x0): first defined hereThe
foo.hheader is indeed included in different classes/files, but there is a ifdef guard, so I don’t understand this.
So How should I do?
There are multiple options:
Declare it in the header, after
Foo, and define it inFoo.cpp.Define it as a
friendinside the class definition.Define it in the header, outside the class definition, and mark it as
inlineto prevent the multiple definition.