首页 > 解决方案 > 有人可以帮我理解这些参数/参数吗?

问题描述

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

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++ 中。

标签: c++treebinary-treebinary-search-tree

解决方案


const在函数声明之后意味着将此函数用于类的 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 的副本传递给函数(因为它的复制构造函数已禁用)。


推荐阅读