5、重载>>,<<符号,实现学生信息的输入输出。
时间: 2023-09-20 16:12:14 浏览: 99
C++程序课程设计—带符号大整数计算器
3星 · 编辑精心推荐
好的,可以的。为了方便起见,我先定义一个学生类的模板,你可以根据自己的需求进行修改:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
string gender;
string major;
double gpa;
friend ostream& operator<<(ostream& os, const Student& stu);
friend istream& operator>>(istream& is, Student& stu);
};
ostream& operator<<(ostream& os, const Student& stu) {
os << "Name: " << stu.name << endl;
os << "Age: " << stu.age << endl;
os << "Gender: " << stu.gender << endl;
os << "Major: " << stu.major << endl;
os << "GPA: " << stu.gpa << endl;
return os;
}
istream& operator>>(istream& is, Student& stu) {
cout << "Please enter student's name: ";
getline(is, stu.name);
cout << "Please enter student's age: ";
is >> stu.age;
cout << "Please enter student's gender: ";
is >> stu.gender;
cout << "Please enter student's major: ";
is >> stu.major;
cout << "Please enter student's GPA: ";
is >> stu.gpa;
return is;
}
```
然后,你可以在主函数中调用这两个重载符号进行输入输出。
```cpp
int main() {
Student stu;
cin >> stu;
cout << stu;
return 0;
}
```
这样,当你运行程序时,就可以输入学生的信息并输出了。
阅读全文