I have a problem when I call operator<< on a pointer. I have searched through SO and asked my question on Google, but all proposed solutions did not solve my problem. To illustrate my problem, please see a simplified piece of my code:
Marker.h:
class Marker {
...
public:
friend std::ostream& operator<<(std::ostream& out, const Marker& marker);
friend std::ostream& operator<<(std::ostream& out, Marker* marker);
};
inline std::ostream& operator<<(std::ostream& out, const Marker& marker) {
out << "Marker " << marker._name << " of type " << marker._type << " at position " << marker._position;
return out;
}
inline std::ostream& operator<<(std::ostream& out, Marker* marker) {
out << *marker;
return out;
}
Landmark.h:
class Landmark {
...
Marker* m_marker;
...
};
Landmark.cpp:
void Landmark::print( std::ostream& out )
{
out << "Marker GENERIC: " << m_marker << std::endl;
//out << "Marker GENERIC: " << *m_marker << std::endl;
}
This does not link under Visual Studio 2008. I get a load of unresolved external symbol errors. If i remove the friend std::ostream& operator<<(std::ostream& out, Marker* marker);, the code compiles, but instead of the expected formatted output, I get only the memory address of the pointer to the marker Marker* Landmark::m_marker. Uncommenting the second line turns my code into incompilable.
How should I overload operator<< so that I get the correct output?
I will be grateful for any help!
Here is a simple example:
And it works as expected.
The error you point at is a linker error, it is telling you that the compiler emitted a call to a method for which no function was emitted.
I will suppose that you have lied to us or that Visual Studio is once again wrong.
inlinemethod, the whole method body should be included before using it, therefore Landmark.cpp should include the methods definitions.minenamespace and not in the global namespace.Something like: