为什么以及如何重载操作符<<用于打印 [英] Why and how to overload operator<< for printing

查看:133
本文介绍了为什么以及如何重载操作符<<用于打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序来实现堆栈。我有一个显示功能。

I have written a program for implementation of stack. And I have one display function in it.

这是我第一次写显示函数的方式:

This is how I wrote display function at first:

template <class t>
void Mystack<t>::display()
{
    for (int i = 0; i <= top; i++)
    {
        std::cout << input[i] << " ";
    }
}

然后我建议开发者写一个显示函数更通用。所以我写显示函数为:

Then I was suggested by developers to write a display function to be more generic. So I wrote display function as:

template <class T>
void Mystack<T>::display(std::ostream &os) const         
{
    for (int i = 0; i <= top; i++)
    {
        os << input[i] << " ";
    }
}

根据我的理解,写上述函数的好处是

As per my understanding the benefit of writing above function is that now I have a generic display function which I can use to display data to console or to a file too.

问题1 :是我的一个显示功能,我可以用来显示数据到控制台或文件。理解正确吗?

Question 1: Is my understanding correct?

现在,另一个建议是写函数:

Now another suggestion is to write function something like:

template <typename T>
friend std::ostream& operator<<(std::ostream& s, Mystack<T> const& d) {
    d.display(s);
    return s;
}

问题2 :以上显示功能?

推荐答案

对于问题1,你的理解是正确的,但是实际改进来自问题2的写作建议:

For question 1, your understanding is correct, but the real improvement comes from question 2's suggestion of writing:

template <typename T>
friend std::ostream& operator<<(std::ostream&, Mystack<T> const& );

这将允许任何人以类似于流式传输的方式流式传输您的类型的对象: p>

That will let anybody stream objects of your type in the same way they would stream anything else:

std::cout << "Hi, my stack is " << stack << ", it has size " << stack.size();

到任何他们想要的讯息串:

to any stream they want:

some_file << "Result of computation is: " << stack;
std::cerr << "Error, invalid stack: " << stack << ", expected: " << some_other_thing;

这篇关于为什么以及如何重载操作符&lt;&lt;用于打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆