class 方法的 C++ 插入运算符

C++ insertion operator for class method

在 C++ 中,有没有办法为 class 方法使用插入运算符?

这个 operator<< 重载正在工作:

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  Complex() {};
  ~Complex() {};
};

我能做到:

int main()
{
  Complex* o = new Complex();

  std::cout << "This is test: " << *o << "." << std::endl; // => This is test: test overload.
}

我知道流操纵器,像这样:

std::ostream& welcome(std::ostream& out)
{
    int data = 1;
    out << "WELCOME " << data << "\r\n";
    return out;
}

int main()
{
  std::cout << "Hello " << welcome; // => "Hello WELCOME 1\r\n"
}

如何将 welcome 方法放入 Complex class 然后如何从 cout 调用它(请注意欢迎方法必须访问一些class成员变量)?

我的试用期:

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  std::ostream& welcome(std::ostream& out) {
    out << "WELCOME " << data << "\r\n";
    return out;
  }

  Complex() { data = 1; };
  ~Complex() {};
private:
  int data;
};

int main()
{
  Complex* o = new Complex();

  std::cout << "This is test2: " << o->welcome << std::endl; // compile error
}

选择不同 << 重载的一种简单方法是使用不同的类型。

#include <iostream>

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  struct extra_info {
      const Complex& parent;
      extra_info(const Complex& p) : parent(p) {}
      friend std::ostream& operator<<(std::ostream& out, const extra_info& ei){
        int i = 1;
        out << "extrainfo " << i;
        return out;
      }
  };
  extra_info extrainfo() {
      return {*this};
  }

  Complex() {};
  ~Complex() {};
};


int main() {
    Complex c;
    std::cout << c << "\n";
    std::cout << c.extrainfo();
}

输出:

test overload
extrainfo 1

我想在您的真实代码中您使用的是成员。因此,助手类型必须持有对 Complex 实例的引用。