有人可以帮助我理解这些 parameters/arguments 吗?

Can someone help me understand these parameters/arguments?

我得到了一些二叉搜索树的代码,并负责为其添加一些功能。但首先,我真的很想更好地理解 parameters/function 给我的其中一个函数的定义。代码:

void printTree( ostream & out = cout ) const
{
    if( isEmpty( ) )
        out << "Empty tree" << endl;
    else
        printTree( root, out );
}
void printTree( BinaryNode *t, ostream & out ) const
{
    if( t != nullptr )
    {
        printTree( t->left, out );
        out << t->element << endl;
        printTree( t->right, out );
    }
}

首先,我不明白为什么在函数声明末尾的括号后有一个 const。另一件对我来说没有意义的事情是第一个函数声明的参数 ostream & out = cout。为什么参数 = 是什么东西,我从来没有见过这个。我不明白 ostream & out 一般指的是什么。 运行 printTree() 没有参数就可以了。为什么即使 printTree 没有不带参数的函数声明也能正常工作?

顺便说一句,这都是在 C++ 中。

const 在函数声明之后意味着可以安全地将此函数用于 class 的 const 对象。此类函数无法更改对象中的任何字段。

ostream & out 是一个全局对象 std::cout,它控制输出到实现定义类型的流缓冲区。简单来说,这个对象可以帮助您在控制台或文件中打印信息。

ostream & out = cout表示cout是默认参数,将在函数中传递。

另一个例子:

void printX(int x = 5)
{
    std::cout << x;
}

如果您不为该函数提供任何参数,那么它将使用默认参数。

printX(10); \ will print 10
printX(); \ will print 5

Why does this work even though there is no function declaration for printTree with no arguments? 那是因为这个函数将使用 cout 来打印出你的树。

I do not understand what the ostream & out is referencing in general.

您不能将 cout 的副本传递给函数(因为它的复制构造函数被禁用)。