c++ - 有人可以帮我理解这些参数/参数吗?
问题描述
我已经获得了一些二叉搜索树的代码,并负责为其添加一些功能。但首先,我真的很想更好地理解给我的一个函数的参数/函数定义。编码:
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
在函数声明之后意味着将此函数用于类的 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 的副本传递给函数(因为它的复制构造函数已禁用)。
推荐阅读
- excel - 将.txt文件转换为.csv而不在excel中打开它的过程是什么?
- python - 如何根据python中的键值计算字典的频率?
- python - Psycopg2 ProgrammingError:SELECT 处或附近的语法错误
- amazon-web-services - 具有 AssociateAddress 权限但不允许重新关联弹性 IP 的 IAM 用户策略选项
- sql - 具有内部联接的 SQL Server 返回的结果比预期的要多
- c# - 切换按钮作为显示隐藏
- javascript - ajax 响应返回 html 响应(XSS 验证码)
- ios - 扩展方法不起作用:“UIImage”类型的值没有成员“压缩”
- asp.net - ASP.NET 集成测试 - TestHost 总是返回 500 内部服务器错误
- bash - 通过查看查找文件中列出的 md5 校验和来删除文件