Reputation: 180
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
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
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