operator <<在构造函数中重载

wan*_*mer 0 c++ constructor cout operator-overloading

我正在调试程序,我想从该模式进行打印:

 std::cout << firstVar << ", " << secondVar << ", " << thirdVar << endl ;
Run Code Online (Sandbox Code Playgroud)

更短,即如果我们编写代码,应该发生同样的事情:

shortPrint(std::cout) << firstVar << secondVar << thirdVar;
Run Code Online (Sandbox Code Playgroud)

注意:变量数量没有限制,它可以是1,它可以是20,所以这也应该有效:

shortPrint(std::cout) << firstVar << secondVar << thirdVar << anotherVar << oneMoreVar;
Run Code Online (Sandbox Code Playgroud)

有人告诉我,最容易做到的就是创建一个名为"shortPrint"的类.

任何人都可以帮我解决这个问题吗?

首先,我要说我只需要实现一个构造函数和运算符<<重载,但我不确定在这种情况下如何做到这一点.

Jea*_*nès 6

是创建shortPrint具有适当重载运算符的类.像这样的东西:

class shortPrint {
  ostream &o;
public:
  shortPrint(ostream &o) : o(o) {}
  template <typename T> shortPrint &operator<<(const T &t) {
    o << t << ',';
    return *this;
  }
  // support for endl, which is not a value but a function (stream->stream)
  shortPrint &operator<<(ostream& (*pf)(std::ostream&)) {
    o << pf;
    return *this;
 }
};
Run Code Online (Sandbox Code Playgroud)

这应该工作(基本上).

要消除额外逗号的问题,请使用:

class shortPrint {
  class shortPrint2{
    shortPrint &s;
  public:
    shortPrint2(shortPrint &s) : s(s) {}
    template <typename T> shortPrint2 &operator<<(const T &t) {
      s.o << ',' << t ;
      return *this;
    }
    shortPrint &operator<<(ostream& (*pf)(std::ostream&)) {
      s.o << pf;
      return s;
    }
  };
  ostream &o;
  shortPrint2 s2;
public:
  shortPrint(ostream &o) : o(o), s2(*this) {}
  template <typename T> shortPrint2 &operator<<(const T &t) {
    o << t;
    return s2;
  }
  shortPrint &operator<<(ostream& (*pf)(std::ostream&)) {
    o << pf;
    return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)