【问题标题】:Passing Multiple Strings in Concatenation Attempt to an ostringstream Parameter在连接尝试中将多个字符串传递给 ostringstream 参数
【发布时间】:2021-04-26 16:21:19
【问题描述】:

我正在尝试创建一个方法,该方法将接受将记录到文件的流(即 ostringstream)参数。

在头文件中,声明为:

static void Log(const std::ostringstream& message, LoggingSeverity severity = LoggingSeverity::info);

但是,当我尝试从另一个类调用该方法时,例如:

SimpleLogger::Log("Name registered.", SimpleLogger::LoggingSeverity::trace);

我收到以下错误:E0415 no suitable constructor exists to convert from "const char []" to "std::basic_ostringstream<char, std::char_traits<char>, std::allocator<char>>"

如果我尝试通过连接字符串(input 的类型为 std::string)来构造调用,如下所示:

SimpleLogger::Log("String to int conversion of [" << input << "] failed.", SimpleLogger::LoggingSeverity::warning);

我收到以下错误:E0349 no operator "&lt;&lt;" matches these operands

从错误中,我了解到 std::ostringstream 参数不喜欢字符串,但我的印象是数据类型将为我提供能够向流提供对象所需的功能,包括,例如,int 值。是否有更好的数据类型来达到预期的效果?或者,对方法的结构化调用是否不正确?

【问题讨论】:

    标签: c++ parameters stream


    【解决方案1】:

    这里的问题是你将一个字符串传递给一个字符串构造函数,这个想法是好的,但是构造函数是显式定义的,所以没有从字符串到字符串流的自动转换,explicit stringstream (const string&amp; str , ios_base::openmode which = ios_base::in | ios_base::out);,你可以找到细节@987654321 @

    至于你的问题,这里是一个示例代码,

    #include <string>
    #include <iostream>
    #include <sstream>
    
    void Logg(const std::ostringstream& message) {
        std::cout<<message.str()<<std::endl;
    }
    
    int main()
    {
        std::string a= "other message";
        Logg(std::ostringstream("some message"));
        Logg(std::ostringstream(a));
        Logg(static_cast<std::ostringstream>(a));
    }
    

    输出

    some message
    other message
    other message
    

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 1970-01-01
      • 2021-01-15
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      相关资源
      最近更新 更多