【问题标题】:Pass this to overloaded << operator将此传递给重载的 << 运算符
【发布时间】:2017-01-18 23:07:41
【问题描述】:

如何在 c++ 类中将this 传递给operator&lt;&lt;?或者我只是做错了(可能)。

例如,在下面的类中,我只有一个循环,它重复地请求并打印一个整数。但是,cout&lt;&lt;this 只是打印了实例的地址,但我想使用定义的运算符重载。

#include<iostream>
using std::cout; using std::endl; using std::cin;

class C {
  int n;
 public:
  C(int n) : n(n) {};
  friend std::ostream& operator<<(std::ostream&, const C&);
  void set_n(int i) { n = i; }
  void play() {
    int input;
    while (true) {
      cout << this;
      cin >> input;
      set_n(input);
    }
  }
};

std::ostream& operator<<(std::ostream& os, const C& c) {
  cout << c.n << "\n";
  return os;
}

int main(int argc, char *argv[]) {
  C c = C(1);
  c.play();
  return 0;
}

【问题讨论】:

  • while (true) cout &lt;&lt; *this;
  • 提示:this 是一个指针,作用类似。

标签: c++ operator-overloading this


【解决方案1】:

this 是一个指针。你需要

cout << *this;

此外,您对operator&lt;&lt; 的定义可能应该使用参数os,而不是始终使用cout。

【讨论】:

    【解决方案2】:

    this 是一个指针。您可能需要取消引用它。

    cout << *this;
    

    【讨论】:

      猜你喜欢
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多