【发布时间】:2017-01-18 23:07:41
【问题描述】:
如何在 c++ 类中将this 传递给operator<<?或者我只是做错了(可能)。
例如,在下面的类中,我只有一个循环,它重复地请求并打印一个整数。但是,cout<<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 << *this; -
提示:
this是一个指针,作用类似。
标签: c++ operator-overloading this