使用 stringstream 作为内联函数内的默认值

发布于 2025-01-08 11:09:26 字数 746 浏览 3 评论 0原文

我正在学习 c++03,我刚刚开始接触 c++。

我想创建一个函数,在字符串流上设置一些属性并返回它(或者可能通过引用传递它),

inline stringstream get_fixed_stream(stringstream ss=stringstream("")) {
    ss.precision(4);
    ss.setf(ios::fixed);
    return ss;
}

所以如果我调用:

stringstream ss = get_fixed_stream()

我接收一个新的字符串,如果我调用

cout = get_fixed_stream(cout)

精度和 setf都设置为cout。

我收到这个错误:

/usr/include/c++/4.4/streambuf:770: error: ‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char, _Traits = std::char_traits<char>]’ is private
/usr/include/c++/4.4/iosfwd:63: error: within this context

i'm on c++03 and i've just begin to approach c++.

i want to to make a function that set some properties on a string stream and return it (or mayebe passing it by reference)

inline stringstream get_fixed_stream(stringstream ss=stringstream("")) {
    ss.precision(4);
    ss.setf(ios::fixed);
    return ss;
}

so if i call:

stringstream ss = get_fixed_stream()

i recive a new strinstring, if i call

cout = get_fixed_stream(cout)

the precision and setf are settet to cout.

i get this error:

/usr/include/c++/4.4/streambuf:770: error: ‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char, _Traits = std::char_traits<char>]’ is private
/usr/include/c++/4.4/iosfwd:63: error: within this context

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月蹉跎了容颜 2025-01-15 11:09:26

std::cout 不是字符串流,不能作为一个字符串流传入。

试试这个

template<typename Stream>
void fix_stream(Stream& stream){ 
    stream.precision(4);
    stream.setf(std::ios::fixed);
}
:::
fix_stream(std::cout);
std::stringstream ss;
fix_stream(ss);

std::cout is not a stringstream and can't be passed in as one.

try this instead

template<typename Stream>
void fix_stream(Stream& stream){ 
    stream.precision(4);
    stream.setf(std::ios::fixed);
}
:::
fix_stream(std::cout);
std::stringstream ss;
fix_stream(ss);
箹锭⒈辈孓 2025-01-15 11:09:26

我建议使用参考(下面的&):

inline stringstream & get_fixed_stream(stringstream & ss)
{
ss.precision(4);
ss.setf(ios::fixed);
return ss;
}

I suggest using a reference (the & below):

inline stringstream & get_fixed_stream(stringstream & ss)
{
ss.precision(4);
ss.setf(ios::fixed);
return ss;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文