Reputation: 642
If I had a simple class with two variables, x and y, and a function ToString() that returns a formatted string with the data. When I call
cout << simpleClass << "\n";
anyone know a way I could have simpleClass.ToString automatically called to return the correctly formatted string? I'm guessing there's a way to do this with operator functions, but I don't know how I would do this.
Upvotes: 5
Views: 535
Reputation: 62985
If you're asking 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();
}
Upvotes: 9
Reputation: 81724
You define
std::ostream& operator <<(std::ostream&, const SimpleClass&)
to call ToString()
, passing the ostream&
, and return the ostream&
.
Upvotes: 2