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
  • 3
  • 17
  • Your question is unclear. What exactly do you want the operator `< – 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
  • 115
  • 6
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
  • 90,891
  • 40
  • 158
  • 247