Reputation: 21
I was wondering if it is possible to overload the << operator
in the need for printing an object in the class in two certain way.
For example, I'm building a domino game so I need to print my cubes with the numbers : [1][6][6][3]
And print the computers cubes : [ ][ ]
Upvotes: 2
Views: 341
Reputation: 6467
Here is one example of overloaded extraction and insertion operators:
/*
Operator: <<
This insertion operator outputs the data members of
class object instantiation in the format:(x,y)
The returning type ostream&, allows
you to chain more then one objects to be printed.
*/
ostream& operator<< (ostream& os, class_name& object_name) {
return os << '(' << object_name.get_data_memberx()
<< ',' << object_name.get_data_membery()
<< ')';
}
/*
Operator: >>
This extraction operator creates an input stream it
inserts to it values for of all the data members of
the class passed by reference and returns it.
Input format: (x,y)
*/
istream& operator>> (istream& is, class_name& object_name) {
char par1, comma, par2;
double x, y;
is >> par1 >> x >> comma >> y >> par2;
// check if any input
if(!is) return is;
// check for valid input format
if (par1 != '(' || comma != ',' || par2 != ')') {
// set failbit to indicate invalid input format
is.clear(ios_base::failbit);
return is;
}
// assign input values to second argument
object_name = class_name(x,y);
return is;
}
You could use the above example and modify the formats to match the desired result.
Upvotes: 3
Reputation: 66981
While the others have answered how to overload operator<<
, it's not clear how to have two different formats. I recommend this: temporary objects.
struct showdomino {
domino& d;
};
std::ostream& operator<<(std::ostream& out, showdomino dom)
{return out << '[' << dom->d.number << ']';}
struct hidedomino {};
std::ostream& operator<<(std::ostream& out, hidedomino dom)
{return out << "[ ]";}
Then usage is vaguely like this:
if (show_it)
std::cout << showdomino{d} << '\n';
else
std::cout << hidedomino{} << '\n';
Upvotes: 2
Reputation: 9082
The << operator used for cout is actually the bitwise left shift operator that is overloaded to obtain this behaviour.
I don't really understand what you want to achieve exactly (a code snippet would have been helpful). But, it seems you want to overload << for an ostream and a YourClass type. You can have something like:
void operator<<(ostream str, YourClass cls) {
// generate required output
}
Note that this acts as a regular function, just the calling syntax is different.
Upvotes: 0