【问题标题】:Can someone help me understand these parameters/arguments?有人可以帮我理解这些参数/参数吗?
【发布时间】:2020-06-20 17:34:12
【问题描述】:

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

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 &amp; out = cout。为什么参数= 的东西,我从来没有见过这个。我不明白ostream &amp; out 一般指的是什么。不带参数运行printTree() 就可以了。为什么即使没有没有参数的 printTree 的函数声明,它仍然有效?

顺便说一句,这都是用 C++ 编写的。

【问题讨论】:

  • 您询问的是每本 C++ 教科书中都涵盖的基本 C++ 基础知识。在您“获得一些二进制搜索树的代码并负责添加一些功能”之前,我想您也会获得足够的材料来教授这些概念?不幸的是,stackoverflow.com 不能替代 C++ 教科书。如果您的教科书对这些语言特征的解释有什么不清楚的地方,请随意引用一段简短的摘录并解释您的问题。您可以在上面找到流行的 C++ 教科书的链接,从中可以找到更多信息。

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


【解决方案1】:

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

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

ostream &amp; 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 &amp; out is referencing in general.

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

【讨论】:

  • 非常感谢,帮了大忙。
  • "ostream & out 是一个全局对象 std::cout" 没有。 ostream&amp; out可以是任意ostreamstd::cout是默认参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多