我正在开发一个 CGI 应用程序,它需要在正文之前发送响应 header ,包括 Content-Length,当然,这在正文完全形成之前是未知的。我可以只使用一个字符串并随时连接,但我喜欢使用 << 运算符,就像 cout
一样,所以我创建了这个小类:
#include <iostream>
using namespace std;
class outbuf {
public:
void operator<<(const char *str) {
this->buffer+= str;
}
void operator<<(const string &str) {
this->buffer+= str;
}
void obsend() {
cout << this->buffer;
this->buffer.clear();
}
private:
string buffer;
};
int main(int argc, char **argv, char** envp) {
outbuf cbout;
string s = " of the output buffer.";
cbout << "This is ";
cbout << "a test" << " ...";
cbout << s;
cbout.obsend();
return 0;
}
问题来自 cbout << "a test" << " ...";
在第二个运算符上,编译器提示 invalid operands of types 'void' and 'const char [5]' to binary 'operator<<'
我了解该错误,但不确定该怎么做。有没有更好的方法来完成我想做的事情? This article看起来很有前途,但我无法理解他在说的某些内容,而且它似乎并不完全适合我正在尝试做的事情。
最佳答案
你的 operator<<
重载应该简单地返回对自身的引用:
outbuf &operator<<(const char *str) {
// ...
return *this;
}
所以现在第一个 <<
的结果operator 是同一个对象,第二个,链接,<<
运营商会很乐意使用。
改变你所有的<<
运算符(operator)以这种方式工作。
关于c++ - CGI 程序的自定义输出缓冲区,运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007536/