为简单起见,使用静态成员函数中的std :: stringstream

时间:2014-04-14 08:02:05

标签: c++ std stringstream

我需要一个接口来将短消息写入日志文件,这些消息通常包含多个部分,例如标识符和值。

为了做到这一点,我创建了一个处理很多次要内容的类,比如创建带时间戳的文件名等等,虽然我不想使用变量参数列表{{1所以我认为我最好的选择是将(int nargs, ...)传递给write函数。

我希望能够将这些调用编写为单行,而不必每次都需要创建std::stringstream,因此我创建了一个静态成员函数来返回我可以使用的字符串流对象使用我的写功能,虽然由于某种原因它不起作用。

MyClass.h

std::stringstream

MyClass.cpp

class MyClass {
public:

    static std::stringstream& stream();
    void write(std::ostream& datastream);

private:

    static std::stringstream* _stringstream;

};

的main.cpp

std::stringstream* MyClass::_stringstream = new std::stringstream();

std::stringstream& MyClass::stream() {
    MyClass::_stringstream->str(std::string());
    return *MyClass::_stringstream;
}

void MyClass::write(std::string data) {
    this->_fhandle << data << std::endl;
}

void MyClass::write(std::ostream& datastream) {
    std::string data = dynamic_cast<std::ostringstream&>(datastream).str();
    this->write(data);
}

代码编译,但在执行应用程序时,我得到MyClass* info = new MyClass(); info->write("Hello, world"); info->write(MyClass::stream() << "Lorem" << ", " << "ipsum"); info->write(MyClass::stream() << "dolor sit" << " amet"); 例外...

1 个答案:

答案 0 :(得分:2)

那是因为你正在创建一个std::stringstream 不是来自std::ostringstream。只需创建一个 std::ostringstreambad_cast应该消失。

话虽如此,多次重复使用std::ostringstream 这样一般不是一个好主意; iostream类是 充满状态,每次使用之间不会重置。它的 最好每次都创建新实例。 (经典的 解决这类问题的方法是创建一个可复制的包装器 class,转发到std::ostream。一个例子 由info->write()返回,因此您可以撰写info->write() << "Hello, world" ...。)