Rockink
Rockink

Reputation: 180

Can operator << be used to design our own way of giving output display

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?

Upvotes: 2

Views: 71

Answers (2)

David G
David G

Reputation: 96845

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.

Upvotes: 0

John Doe
John Doe

Reputation: 85

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!

Upvotes: 3

Related Questions