重载<<
时间: 2023-07-08 12:21:49 浏览: 34
重载<<(输出运算符)的语法如下:
```
ostream& operator<< (ostream& os, const YourClass& obj) {
os << obj.someMemberVariable;
return os;
}
```
其中,`YourClass` 是你要重载输出运算符的类名,`someMemberVariable` 是该类的一个成员变量,`os` 是输出流对象(例如 `cout`),`obj` 是要输出的对象。
在重载输出运算符时,你需要遵循以下注意事项:
1. 重载函数必须声明为类的友元函数或全局函数。
2. 函数必须返回一个 `ostream` 引用,以便可以使用链式语法。
3. 第一个参数必须是 `ostream` 引用,并且是非常量的,以便可以修改流对象。
4. 第二个参数必须是要输出的对象的常量引用。
5. 在函数体中,使用 `os` 对象来输出要输出的变量或对象。
例如,下面的代码演示了如何重载输出运算符:
```c++
#include <iostream>
using namespace std;
class Point {
public:
Point(int x = 0, int y = 0) : m_x(x), m_y(y) {}
friend ostream& operator<< (ostream& os, const Point& p) {
os << "(" << p.m_x << ", " << p.m_y << ")";
return os;
}
private:
int m_x;
int m_y;
};
int main() {
Point p(3, 4);
cout << "The point is: " << p << endl;
return 0;
}
```
输出结果为:
```
The point is: (3, 4)
```