[英]C++ stringstream
How does stringstream work when you do this: 执行此操作时,stringstream如何工作:
stringstream ss;
ss << "123" << "abc";
Does it create a throwaway "123abc" string or does it do both operations consecutively to the stringstream? 它是否会创建一个一次性“123abc”字符串,或者它是否会连续执行两个字符串流操作?
I would like to replicate that functionality but no overload I do seems to work with two parameters like the above code... 我想复制那个功能,但没有重载我似乎使用两个参数,如上面的代码...
It's the equivalent of doing two seperate function calls of the << operator: 它相当于对<<运算符执行两个单独的函数调用:
(ss.operator<<("123")).operator<<("abc")
so yes, it does both operations "consecutively". 所以是的,它会“连续”完成两项操作。
Actually it is equivalent to this: 实际上它等同于:
std::operator<<(std::operator<<(ss, "123"), "abc");
Note that there is no member function which takes const char*
as argument. 请注意, 没有成员函数将const char*
作为参数。 It is a non-member function, and ss
is passed to it as first argument and const char*
is passed as second argument. 它是一个非成员函数, ss
作为第一个参数传递给它, const char*
作为第二个参数传递。 The function returns std::ostream&
which then passed to it again. 该函数返回std::ostream&
然后再次传递给它。 It is more like this: 它更像是这样的:
print( print (ss, "123"), "abc"); //just for clarity
which means there are two function calls. 这意味着有两个函数调用。 Replace print
with std::operator<<
. 用std::operator<<
替换print
。 Everything will be clear now. 现在一切都会很清楚。
Hope that helps. 希望有所帮助。
The other answer which says this: 另一个答案说:
(ss.operator<<("123")).operator<<("abc") //copied from other answer (wrong)
is wrong! 是错的! It is wrong because it assumes that operator<<
which takes const char*
as argument is a member function which is not true! 这是错误的,因为它假设operator<<
以const char*
作为参数是一个不正确的成员函数!
std::stringstream::operator<<(const char*)
returns a std::stringstream&
. std::stringstream::operator<<(const char*)
返回一个std::stringstream&
。
This technique lets you "chain" it. 这种技术可以让你“链接”它。
This is not quite true -- but it is pretty much equivalent to the truth for your purposes. 这不是真的 - 但它几乎等同于你的目的的真相。
A slightly more accurate statement is that std::stringstream& operator<<(std::stringstream&, const char*)
can be chained. 稍微更准确的说法是std::stringstream& operator<<(std::stringstream&, const char*)
可以链接。
An even more accurate statement is that ostream& operator<<(ostream&, const char*)
exists, and std::stringstream
is an ostream
, then overload resolution on <<
calls it. 一个更准确的说法是ostream& operator<<(ostream&, const char*)
存在, std::stringstream
是一个ostream
,然后<<
on <<
重载ostream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.