Java’s toString() method unfortunately has no standard equivalent for C++ structs and classes. If you have custom structs/classes and want to print some debugging information of that classes to standard output, the default way is to “concatenate” the properties of interest into an output stream. Say we have a struct BeadSequence (this is taken from the beads exercise in the USACO training camp) which represents a sequence of beads which has a length and a color:
struct BeadSequence
{
int length;
char color;
BeadSequence() : length(0), color('') {}
BeadSequence(int length, char color) : length(length), color(color) {}
};
If you want some debugging information on an instance (say beadSequence) of that class, you will normally do it like this:
BeadSequence beadSequence(10, 'w'); // white sequence of length 10
std::cout << "c=" << beadSequence.color << ", l=" << beadSequence.length << std::endl;
You need to repeat this every time you want some information on a bead sequence – terribly cumbersome! What you would want to have instead is:
BeadSequence beadSequence(10, 'w'); // white sequence of length 10
std::cout << beadSequence<< std::endl;
BeadSequence should “know” the interesting debugging information. To this end, you may override the operator<< which is used in conjunction with std::ostream objects to output data:
std::ostream& operator<<(std::ostream &stream, const BeadSequence &object)
{
stream << "c=" << object.color
<< ", l=" << object.length;
return stream;
}
The following is a minimal working example:
#include <iostream>
struct BeadSequence
{
int length;
char color;
BeadSequence() : length(0), color('') {}
BeadSequence(int length, char color) : length(length), color(color) {}
};
std::ostream& operator<<(std::ostream &stream, const BeadSequence &object);
int main()
{
BeadSequence beadSequence(10, 'w');
std::cout << beadSequence << std::endl;
return 0;
}
std::ostream& operator<<(std::ostream &stream, const BeadSequence &object)
{
stream << "c=" << object.color << ", l=" << object.length;
return stream;
}