在 c++ 中创建函数输出到指定源
我想要一个函数,将某些信息输出到输入到该函数的特定指定源。在代码中,我的意思是:
function output( source ) {
source << "hello" << endl;
}
其中 source 可以是 ofstream
或 cout
。这样我就可以像这样调用这个函数:
output(cout)
或 ofstream otp ("hello");输出(otp)
我的问题是,如何描述source
以使这项工作正常进行?可以公平地假设 source
始终是 std
类的成员,
谢谢!
I want to have a function that outputs certain pieces of information to a specific designated source that is inputted to the function. In code, what I mean is:
function output( source ) {
source << "hello" << endl;
}
where source can be a ofstream
or cout
. So that I can call this function like so:
output(cout)
or ofstream otp ("hello"); output(otp)
My question is, how do I characterize source
to make this work? It's fair to assume that source
will always be a member of the std
class
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
甚至:
or even:
将你的函数写为:
然后你可以使用它:
顺便说一句,如果
output
函数有很多行,那么你可以将它写为:重点是它应该返回
source< /代码>。在早期版本中,该函数返回
source
。Write your function as:
Then you can use it as:
By the way, if the
output
function has many lines, then you can write it as:The point is that it should return
source
. In the earlier version, the function returnssource
.您应该传递
std::ostream&
作为参数You should pass an
std::ostream&
as argument如果这是一个成员函数,其目的是转储有关它所属类的对象的数据,请考虑将其重命名为
operator<<
。因此,不要尝试这样做:
这样,您可以使用更自然的语法显示类的状态:
而不是笨重的语法
If this is a member function, the point of which is to dump data about objects of the class of which it is a member, consider renaming it to
operator<<
. So, instead ofrather, try this:
That way, you can display the state of your class using a more natural syntax:
instead of the klunky
恕我直言,重定向输出应该在用户级别完成。像这样编写你的 C++:
当执行应用程序时,用户可以将输出重定向到他想要的任何内容,例如文件:
IMHO, redirecting output should be done at the user level. Write your C++ like this:
And when executing the application, user can redirect the output to whatever he wants, say a file: