为简单起见,使用来自静态成员函数的 std::stringstream
Using a std::stringstream from static member function for simplicity
我需要一个接口来将短消息写入日志文件,消息通常包含多个部分,例如标识符和值。
为了做到这一点,我创建了一个处理很多小东西的类,例如创建带有时间戳的文件名等,尽管我不想使用变量参数列表(int nargs, ...)
,所以我认为我最好的选择是将std::stringstream
传递给 write 函数。
我希望能够将这些调用编写为单行,而不必每次需要执行此操作时都创建std::stringstream
,因此我创建了一个静态成员函数来返回一个字符串流对象,我可以与我的写入函数一起使用,尽管由于某种原因它不起作用。
MyClass.h
class MyClass {
public:
static std::stringstream& stream();
void write(std::ostream& datastream);
private:
static std::stringstream* _stringstream;
};
我的班级.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);
}
主.cpp
MyClass* info = new MyClass();
info->write("Hello, world");
info->write(MyClass::stream() << "Lorem" << ", " << "ipsum");
info->write(MyClass::stream() << "dolor sit" << " amet");
代码可以编译,但是在执行应用程序时,我得到了一个std::bad_cast
异常...
那是因为你正在创建一个std::stringstream
,它不是从std::ostringstream
派生的。 只需创建一个 std::ostringstream
,bad_cast
应该消失。
话虽如此,多次重复使用std::ostringstream
像这样通常不是一个好主意;iostream 类是充满状态,每次使用之间不会重置。 它最好每次都创建新实例。 (古典这种事情的解决方案是创建一个可复制的包装器类,转发到std::ostream
。 这个的一个例子由 info->write()
返回,因此可以写info->write() << "Hello, world" ...
。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- std::异步与非静态成员函数
- C++无效使用非静态成员函数?
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 未使用的C++未优化的静态成员函数/变量
- C++:如何返回指向非静态成员函数的指针?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 函数静态成员变量
- 隐藏模板化的辅助函数——静态成员或未命名的命名空间