Johan Johan - 2 months ago 13
C++ Question

Can a user-defined class have custom behavior with std::cout <<?

Suppose I have a class

Crate
, and it has two members,
width
and
height
. Now suppose I want the line
std::cout << myCrate << '\n';
to print this:

#---#
| |
| |
#---#


if
myCrate
has
width = 5
and
height = 4
. Different
width
s and
height
s should result in different crate sizes. Can I define this behavior, e.g. through overloading the
<<
operator? How would I go about doing this?

Keep in mind that this is a generic example and not specific to the
Crate
class above.

Answer

Yes, you can do it by overloading operator<< as shown below. By declaring the function as a friend of Crate, it will have access to all private data members, allowing you to represent the data however you see fit.

Crate.hpp

class Crate {
   ...
   friend std::ostream& operator<< ( std::ostream& os, const Crate& c );
   ...
}

Crate.cpp

std::ostream& operator<< ( std::ostream& os, const Crate& c ) {
   os << "whatever you want to print"

   return os;
}
Comments