流插入和流提取运算符成员函数
时间: 2023-08-16 09:14:32 浏览: 52
流插入和流提取运算符是 C++ 中重要的 I/O 操作,可以通过重载类的流插入和流提取运算符成员函数实现对该类对象的输入输出操作。下面是一个示例代码:
```c++
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
friend ostream& operator<<(ostream& os, const Person& p);
friend istream& operator>>(istream& is, Person& p);
};
ostream& operator<<(ostream& os, const Person& p) {
os << "Name: " << p.name << ", Age: " << p.age << endl;
return os;
}
istream& operator>>(istream& is, Person& p) {
cout << "Enter name: ";
is >> p.name;
cout << "Enter age: ";
is >> p.age;
return is;
}
int main() {
Person p;
cin >> p;
cout << p;
return 0;
}
```
在上面的代码中,`Person` 类定义了两个友元函数 `operator<<` 和 `operator>>`,分别用于流插入和流提取操作。在 `operator<<` 函数中,使用 `os` 输出流将对象的属性输出到屏幕上;在 `operator>>` 函数中,使用 `is` 输入流从键盘上读取对象的属性。在 `main()` 函数中,首先使用 `cin >> p` 进行对象属性的输入,然后使用 `cout << p` 进行对象属性的输出。