C ++ format for cout << Automatically

If I had a simple class with two variables x and y and the ToString () function, which returns a formatted data string. When i call

cout << simpleClass << "\n";

Does anyone know a way that I could have simpleClass.ToString is automatically called to return a correctly formatted string? I suppose there is a way to do this using operator functions, but I don't know how to do this.

+5
source share
2 answers

If you ask how to define such an operator,

template<class CharT, class TraitsT>
std::basic_ostream<CharT, TraitsT>&
operator <<(std::basic_ostream<CharT, TraitsT>& os, SimpleClass const& sc)
{
    return os << sc.ToString();
}
+9
source

You define

std::ostream& operator <<(std::ostream&, const SimpleClass&)

to call ToString(), transfer ostream&and return ostream&.

+2

All Articles