【问题标题】:No matching function call for ostringstream `.str()`ostringstream `.str()` 没有匹配的函数调用
【发布时间】:2018-03-24 12:03:32
【问题描述】:

我有一个定义为的函数

void writeSite(string& site, const string& contentType);

现在我正在使用std::ostringstream 函数构建我的字符串。

完成字符串后,我想调用writeSite 函数。但我收到以下错误:

no matching function for call to ‘writeSite(std::basic_ostringstream<char>::__string_type, const char [17])’
   writeSite(body.str(), "application/json");

如果我先将ostringstream 保存到一个新的std::string 变量中,然后调用writeSite 函数,我可以解决这个问题。

但我想知道,是否有更好的选择?

  std::ostringstream body;

  body << "{";

  // some more string building

  body << "}";

  std::string sbody = body.str();

  writeSite(sbody, "application/json");

【问题讨论】:

  • 抱歉,这是为什么需要minimal reproducible example 的一个典型例子。我半信半疑你自己也能发现这个小错误。
  • 可以把函数的签名改成void writeSite(const string&amp; site, const string&amp; contentType);吗?

标签: c++ ostringstream


【解决方案1】:

当你这样做时

writeSite(body.str(), "application/json");

body.str() 返回的字符串对象是临时的。并且非常量引用不能绑定到临时对象。

一个简单的解决方案是使site 参数const 就像您为contentType 参数所做的那样(否则会遇到同样的问题)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2021-09-21
    • 2016-11-23
    • 2016-08-08
    • 2014-03-12
    • 2015-03-17
    • 2018-08-04
    相关资源
    最近更新 更多