【问题标题】:C++ insertion operator for class method类方法的 C++ 插入运算符
【发布时间】:2020-05-28 19:20:07
【问题描述】:

在 C++ 中有没有办法将插入运算符用于类方法?

这个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 类中,然后如何从cout 调用它(请注意welcome 方法必须访问一些类成员变量)?

我的审判:

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
}

【问题讨论】:

  • 请出示真实代码。你的“正常”重载是一个成员函数,不能像这样工作
  • mymethod 可以返回一个字符串,然后您可以执行std::cout &lt;&lt; c.mymethod() &lt;&lt; " then other stuff"。请澄清,它不是很清楚你的问题是什么
  • 您的程序的预期输出究竟是什么?
  • 你可以编写一个自定义的操纵器来实现这样的效果。 accu.org/index.php/journals/1769
  • 您不必将其留在那里作为历史记录,您也不必在您的问题中添加“更新”。如果有人想查看编辑历史记录,可以在这里进行:stackoverflow.com/posts/62072866/revisions

标签: c++ iostream ostream insertion


【解决方案1】:

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

#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 实例的引用。

【讨论】:

  • hmm.. 我们可以通过使用非递归操纵器来消除警告吗?不像我们在嵌套类的情况下需要一个参数。或者可以删除 ei 参数的名称
  • c.welcome(std::cout) 在我的机器上编译失败:“错误:无法将‘std::ostream {aka std::basic_ostream}’左值绑定到‘std::basic_ostream&&’”
  • @Swift-FridayPie 对不起,我不明白。我没有收到警告,也没有递归
  • @Daniel 抱歉你把代码改的太快了,我懒得认真写答案,我的错,我会删除它
  • @idclev463035818:我对您的意见很感兴趣:理论上,这个 extrainfo 解决方案比创建字符串流并将其返回给 cout 更好(运行速度更快)?
猜你喜欢
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 2012-09-19
  • 2016-05-18
  • 2015-12-29
相关资源
最近更新 更多