c – 用于类的自定义流操纵器
作者:互联网
我正在尝试编写一个简单的审计类,它通过运算符<<并在收到如下自定义操纵器后写入审计:
class CAudit
{
public:
//needs to be templated
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
//attempted manipulator
static CAudit& write(CAudit& audit) {
//write contents of audittext to audit and clear it
return audit;
}
private:
std::stringstream audittext;
};
//to be used like
CAudit audit;
audit << "Data " << data << " received at " << time << CAudit::write;
我认识到我的代码中的重载运算符不返回流对象,但是想知道是否仍然可以使用类似语法的操作符.目前编译器正在看到’<<<作为二元右移运算符.
感谢您的任何意见,
帕特里克
解决方法:
为了使它工作,你必须添加运算符的重载<<对于功能,
而不是从它调用函数:
class CAudit
{
//...other details here as in original question
CAudit& operator << (CAudit & (*func)(CAudit &))
{
return func(*this);
}
};
CAudit audit;
audit << "some text" << CAudit::write;
标签:manipulators,c,stream 来源: https://codeday.me/bug/20191002/1843005.html