我正在尝试编写一个简单的审计类,它通过运算符 << 获取输入并在收到这样的自定义操纵器后编写审计:
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;
关于c++ - 类的自定义流操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1328568/