In Java, when a class overrides .toString()
and you do System.out.println()
it will use that.
class MyObj { public String toString() { return "Hi"; } } ... x = new MyObj(); System.out.println(x); // prints Hi
How can I accomplish that in C++, so that:
Object x = new Object(); std::cout << *x << endl;
Will output some meaningful string representation I chose for Object
?
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.
By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.
std::ostream & operator<<(std::ostream & Str, Object const & v) { // print something from v to str, e.g: Str << v.getX(); return Str; }
If you write this in a header file, remember to mark the function inline: inline std::ostream & operator<<(...
(See the C++ Super-FAQ for why.)
Alternative to Erik's solution you can override the string conversion operator.
class MyObj { public: operator std::string() const { return "Hi"; } }
With this approach, you can use your objects wherever a string output is needed. You are not restricted to streams.
However this type of conversion operators may lead to unintentional conversions and hard-to-trace bugs. I recommend using this with only classes that have text semantics, such as a Path
, a UserName
and a SerialCode
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With