重载输入输出运算符
时间: 2023-06-29 11:14:24 浏览: 51
重载输入输出运算符是C++中的一个重要特性,可以让自定义的类支持像标准库中的类一样使用输入输出运算符。重载输入运算符可以让用户从标准输入流中读取数据并初始化对象的属性,而重载输出运算符则可以让用户将对象的属性输出到标准输出流中。
重载输入输出运算符的示例代码如下:
```c++
#include <iostream>
using namespace std;
class MyClass {
public:
int x, y;
// 重载输入运算符
friend istream& operator>>(istream& input, MyClass& obj) {
input >> obj.x >> obj.y;
return input;
}
// 重载输出运算符
friend ostream& operator<<(ostream& output, const MyClass& obj) {
output << "(" << obj.x << ", " << obj.y << ")";
return output;
}
};
int main() {
MyClass obj;
cout << "Enter x and y: ";
cin >> obj;
cout << "The object is: " << obj << endl;
return 0;
}
```
在上面的代码中,我们定义了一个名为`MyClass`的类,并在其中重载了输入输出运算符。在`main()`函数中,我们创建了一个`MyClass`对象`obj`,并使用输入运算符从标准输入流中读取数据并初始化`obj`的属性。然后,我们使用输出运算符将`obj`的属性输出到标准输出流中。
注意,重载输入输出运算符时,我们需要使用`friend`关键字来声明它们为类的友元函数,以便它们能够访问类的私有成员。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)