-2

I can overload the return value for example on cout function? I have for example this class :

class Xxx
{
   string val = "3";
}

Now I would like to return "3" on cout without other method. I want that :

Xxx myVar;
cout<<myVar;

prints "3" as its result.

simonc
  • 41,632
  • 12
  • 85
  • 103
Emanuele Pavanello
  • 785
  • 1
  • 9
  • 22
  • 2
    Have you tried researching? Here's a hint, and this isn't C at all: http://stackoverflow.com/questions/4421706/operator-overloading – chris May 30 '13 at 09:03

1 Answers1

1

The usual approach is to overloas ostream& operator<<(ostream&, T). Here, val is made public for simplicity:

class Xxx
{
 public:
   std::string val = "3";
}

#include <ostream>
std::ostream& operator<<(std::ostream& o, const Xxx& x)
{
  return o << x.val;
}

Then

Xxx x;
std::cout << x << std::endl; // prints "3"

This approach means you can also stream instances of Xxx to types of output stream other than std::cout, for instance, files.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Lately I've been using `template std::basic_ostream& operator<<(std::basic_ostream& os, const Xxx&)` where possible. Do you think this is worth bothering with? – BoBTFish May 30 '13 at 09:14
  • 1
    @BoBTFish I would say it is definitely worth it, why limit oneself to `char`. Probably too much for OP to handle at the moment though. – juanchopanza May 30 '13 at 09:18