CGI程序的自定义输出缓冲区,运算符重载



我正在开发一个 CGI 应用程序,它需要在正文之前发送响应标头,包括 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<<'我理解错误,但不确定如何处理它。有没有更好的方法来完成我想要做的事情?这篇文章看起来很有希望,但我无法理解他在说什么,而且它似乎并不完全符合我想要做的事情。

您的operator<<重载应该只返回对自身的引用:

outbuf &operator<<(const char *str) {
// ...
    return *this;
}

因此,现在第一个<<运算符的结果是相同的对象,第二个链接的<<运算符将愉快地使用它。

将所有<<运算符更改为以这种方式工作。

最新更新