在学习了JAVA的toString函数后,我也想在C++中实现类似的功能,显然,我们需要重载 << 来解决问题。
#include <iostream>
using namespace std;
struct Node {
int x, y;
Node(int a, int b) {
x = a;
y = b;
}
friend std::ostream& operator << (ostream& co, Node a) {
return co << a.x << " " << a.y;
};
};
int main(void) {
Node student(1, 2);
cout << student;
cin.get();
}
我们知道,<<运算符返回一个流(所以我们才能有这样的使用 cout << a << b;)
所以只要按代码中一样重载<<,返回一个新流就可以了。
over~