Let's say I make a class, like, which contains a char array. Now, what operator handles this:
myClass inst;
cout << inst;
At the "cout << inst;" what is called, by simply the class' name? Thanks.
What is called is std::ostream &operator<<(std::ostream &, myClass const &)
. You can overload this if you want.
By creating a friend output operator, as in the following example.
#include <iostream>
class MyClass {
friend std::ostream & operator<<(std::ostream &out, const MyClass &inst);
public:
// ... public interface ...
private:
char array[SOME_FIXED_SIZE];
};
std::ostream & operator<<(std::ostream &out, const MyClass &inst)
{
out.write(inst.array, SOME_FIXED_SIZE);
return out;
}
Please not this makes some assumptions about what you mean by "char array", it is greatly simplified if your char array is actually nul (0 character) terminated.
Update: I will say this is not strictly a return value for the class, but rather a textual representation of the class -- which you are free to define.
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