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

标签 c++ cgi

我正在开发一个 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/

相关文章:

c++ - 更新已移植到 Visual Studio 2013 的 native MFC 应用程序 GUI

c++ - 查找两个文件中内容之间的差异

c++ - 使用不带参数的模板名称

html - 使用超链接的名称

javascript - 将 href perl 变量转换为普通标量变量

c++ - 尝试运行在 Netbeans 中编译的 C++ 程序时出错

c++ - 改变字符指针的值

python - 在共享虚拟主机上将 Flask 部署为 CGI

http - 为什么选择 FastCGI 而不是使用编译语言或守护进程的 CGI

linux - 有没有办法在 Linux + Apache 上执行 .exe CGI 应用程序