如何重载运算符<<使其像ostream一样工作

3
我正在实现一个类,并且希望使用 "<<" 向实例传递一些参数。
例如,
terminal term;
term << "Hello World!" << '\n';

代码在下面:
class terminal {
    template <typename T>
    terminal& operator << (T& t) {
        std::cout << t;
        return *this;
    }
};

基本上,我希望成为一个流而不是成为流的一部分。(不是cout << term;)
(对不起,我忘了说明我的问题)问题是,如果有数字(如int、char等),它可以很好地处理字符串,但编译会失败。
如果我们使用上面的例子,编译器会抱怨:
无效的二进制表达式操作数('终端'和'int')

2
你的代码有什么问题? - Angew is no longer proud of SO
4
T& t 改为 const T& 就可以了。 - n. m.
你能同时发布产生错误的代码吗? - Angew is no longer proud of SO
这个链接可能会解决你的问题。 - Sardeep Lakhera
@n.m. 谢谢!你刚刚解决了我的问题!它需要是 const T&。 - 0xBBC
@Angew,非常抱歉我甚至忘记写下我的问题。不过问题已经解决了,还是非常感谢你们。 - 0xBBC
2个回答

2

为了使运算符<<(例如term << "hello" << std::endl;)的排序工作,我建议更改如下:

namespace foo {

class terminal {    
  std::ostream &strm;
public:
  terminal(std::ostream &strm_) : strm(strm_) {}
  terminal() : strm(std::cout) {}

  template <typename T>
  friend std::ostream& operator<<(terminal &term, T const &t);
};

template <typename T>
std::ostream& operator<<(terminal &term, T const &t) {
  term.strm << t;
  return term.strm;
}

}

Live Demo


谢谢。这个实现考虑了 ostream,比我的好。 - 0xBBC

1
问题在于你的operator <<接受非const引用作为参数,这意味着它只能绑定到左值上。因此像非字符串字面量这样的东西是不行的。如果你不需要修改参数,请改用const &。语言有一个特殊规则,允许左值引用到const也可以绑定到右值。
terminal& operator << (const T& t) {
    std::cout << t;
    return *this;
}

如果您确实需要修改参数,请使用不同的方法而不是<<。在<<期间修改流式传输参数的界面将非常反直觉且难以维护。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接