2

Like

std::cout<<type_variable 

calls cout and have that variable or content to be printed on the screen.

What if I wanted to design my own way of handling how to give output. I used function to create my own way of giving output such as

std::cout<<string(5,'-')<<std::endl;
std::cout<<"name"<<std::endl;
std::cout<<string(5,'-')<<endl;

But, I would love to have operator "<<" or similar to provide the display. And create operator to give output as

out<<some_output 

I couldn't find answer to this one and it may seem inadequate study on programming, but is it possible?

Rockink
  • 180
  • 4
  • 17
  • Your question is unclear. What exactly do you want the operator `<<` to do? `<<` can be overloaded like any other operator. Read [here](http://stackoverflow.com/questions/4421706/operator-overloading). – Daniel Apr 26 '14 at 23:27
  • Yes. Do you want a way to send your custom class to `cout`, or a way to use your custom class as a custom formatter in place of `cout`? – aschepler Apr 27 '14 at 02:14

2 Answers2

3

Easy, you can make a manipulator:

std::ostream& custom_output(std::ostream& os)
{
    return os << std::string(5, '-') << std::endl
              << "name"              << std::endl
              << std::string(5, '-') << std::endl;
}

Then you can write to it like this:

std::cout << custom_output;

Hope this helped!

John Doe
  • 85
  • 6
  • what if i wanted to pass my string or int, and, how can i call that one? – Rockink Apr 26 '14 at 23:52
  • @Rockink Then you will have to do something a bit different: Change `custom_output` into a class and overload the `<<` operator. Use the class's constructor to send the input. Then you will do `std::cout << custom_output("name");` – John Doe Apr 27 '14 at 00:03
0

You can do it like the other answer said. Here's another way:

class X
{
public:
    X(std::string const& _name) : name(_name) { }
    friend std::ostream& operator<<(std::ostream& os, const X& x)
private:
    std::string name;
};

std::ostream& operator<<(std::ostream& os, const X& x)
{
    return os << x.name;
}

int main()
{
    X x("Bob");
    std::cout << x; // "Bob"
}

Customize for your own use.

David G
  • 94,763
  • 41
  • 167
  • 253