-1

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 widths and heights 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.

Johan
  • 343
  • 1
  • 4
  • 13
  • 1
    Through overloading the `<<` operator. – LogicStuff Oct 01 '16 at 20:11
  • I'd like more specific instructions. – Johan Oct 01 '16 at 20:12
  • 1
    You will find more specific instructions in the book you are learning C++ from. stackoverflow.com is not a code-writing service. – Sam Varshavchik Oct 01 '16 at 20:14
  • 1
    Use your favorite search engine to look for e.g. `c++ overload operator <<`. Or [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to read. – Some programmer dude Oct 01 '16 at 20:14
  • Try to scrape up something yourself first, consult SO only if something goes wrong. – LogicStuff Oct 01 '16 at 20:14
  • "Look it up". Thanks for the great advice guys, hadn't thought of that \s – Johan Oct 01 '16 at 20:16
  • 1
    We will gladly help you if you only show some effort. If all you want is a ready-made solution then this isn't the right place. – Some programmer dude Oct 01 '16 at 20:19
  • If you read the question you'll find that this is a generic example, and I'm looking for a quick instructive piece of example code. I'm not asking you to do my work for me, I'm asking you to help me understand a concept with an example. Excuse me so much if that was too much to ask of you your royal excellencies. – Johan Oct 01 '16 at 20:23

1 Answers1

3

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;
}
Ben Wainwright
  • 4,224
  • 1
  • 18
  • 36