[英]How to pass string retrieved from stringstream by reference?
I have following function 我有以下功能
void myfun(std::string &str);
and I'm calling this functionas follows: 我称这个功能如下:
stringstream temp("");
temp << "some string data" ;
myfun(temp.str());
but I'm getting following error: 但我收到以下错误:
error: no matching function for call to ‘myfun(std::basic_stringstream<char>::__string_type)’
and 和
no known conversion for argument 1 from ‘std::basic_stringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘std::string& {aka std::basic_string<char>&}’
How can I pass this string by reference? 如何通过引用传递此字符串?
Why you need this? 为什么需要这个? Why
myfun
receives reference, but not const
? 为什么
myfun
收到引用,而不是const
? std::stringstream::str
returns std::string
, that is temporary object and cannot be binded to lvalue-reference
. std::stringstream::str
返回std::string
,它是临时对象,不能绑定到lvalue-reference
。 You can send copy to function 您可以发送副本到功能
std::string tmp = temp.str();
fun(tmp);
If you don't want to modify str
in function fun
you can rewrite it's signature to 如果您不想在函数
fun
修改str
,可以将其签名重写为
void myfun(const std::string& str)
str
returns by value, ie a copy of the internal string in temp
. str
按值返回,即temp
内部字符串的副本。 You can't pass a copy by non- const
reference. 您不能通过非
const
引用传递副本。
You can modify the function signature to: 您可以将函数签名修改为:
void myfun(const std::string &str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.