如何将对 `std::cout` 的引用存储为类成员
我正在使用一个旨在像这样使用的类:
Output() << "Hello.\n";
在其 operator<<
中,我明确使用 std::cout
,但我想要一个静态的解析为“std::cout”的类成员,这样我就可以做这样的事情:
copy(some_string_set.begin(), some_string_set.end(), ostream_iterator<string>(Output::m_stream, ", "));
或类似的事情(在修复静态数据成员之前我无法修复底线。
我什至尝试过auto
,但是 GCC 抛出了一个
错误:“std::cout”不能出现在常量表达式中
。我怎样才能做我想做的事? (重点是不必在我的代码中全部使用 std::cout ,而是让所有输出都通过 Output 类)
I'm using a class meant to be used like this:
Output() << "Hello.\n";
In its operator<<
I explicitely use std::cout
, but I'd like to have a static class member that resolves to `std::cout´ so I can do stuff like this:
copy(some_string_set.begin(), some_string_set.end(), ostream_iterator<string>(Output::m_stream, ", "));
or something similar (I can't fix the bottom line until I get the static data member fixed.
I even tried auto
, but GCC threw a
error: 'std::cout' cannot appear in a constant-expression
at me. How can I do what I want? (the point is not having to use std::cout
all through my code, but have all output go through the Output class)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这里工作得很好。
Works fine here.
将其存储为
std::ostream*
。有时人们将引用存储为成员。这很容易出错,因为引用不能重新分配,这会导致赋值运算符做错误的事情。
Store it as
std::ostream*
.Sometimes people store references as members. This is error prone because the reference can not be reassigned, which causes assignment operator to do the wrong thing.
您应该存储一个
std::ostream &
。You should store a
std::ostream &
.