为什么以及如何重载operator <<进行打印

tan*_*anz 5 c++ operator-overloading friend

我编写了一个用于实现堆栈的程序.我有一个显示功能.

这是我最初编写显示功能的方式:

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

然后我被开发人员建议编写一个更通用的显示函数.所以我写了显示功能:

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

根据我的理解,编写上述功能的好处是,现在我有一个通用的显示功能,我可以使用它来向控制台或文件显示数据.

问题1:我的理解是否正确?

现在另一个建议是写函数类似于:

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

问题2:具有上述显示功能有什么好处?通过具有上述显示功能,我能够实现什么?

Bar*_*rry 6

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

template <typename T>
friend std::ostream& operator<<(std::ostream&, Mystack<T> const& );
Run Code Online (Sandbox Code Playgroud)

这将让任何人以与传输其他内容相同的方式流式传输您的类型的对象:

std::cout << "Hi, my stack is " << stack << ", it has size " << stack.size();
Run Code Online (Sandbox Code Playgroud)

到他们想要的任何流:

some_file << "Result of computation is: " << stack;
std::cerr << "Error, invalid stack: " << stack << ", expected: " << some_other_thing;
Run Code Online (Sandbox Code Playgroud)


OJF*_*ord 5

首先 - 是的.通过采取std::ostream&参数,您可以输出到任何派生流过,像std::ofstream,或者std::cout,std::cerr.

使用operator<<允许您使用该运算符.考虑:

mystack<int> stackOfInts;
//...
std::cout << "Stack contents:" << std::endl << stackOfInts << std::endl;
Run Code Online (Sandbox Code Playgroud)

它比"标准"函数调用更具惯用性.

返回流允许操作符的链接,如上例所示.链接有效地将调用结果传递给operator<<另一个:

operator<<( operator<<("Stack contents:", std::endl), stackOfInts ) );
Run Code Online (Sandbox Code Playgroud)

如果这个重载的调用也没有返回std::ostream&,那么就没有办法:

operator<<( resultOfAbove, std::endl );
Run Code Online (Sandbox Code Playgroud)

声明函数a friend允许其定义使用私有成员.如果没有这个,你就必须为每个私人成员写一个公共的getter.