2024年4月28日发(作者:)

struct重载运算符

C++中的struct可以像class一样定义成员函数和重载运算符。下面

介绍struct的运算符重载。

1.重载输出运算符。

重载输出运算符可以使得在输出struct对象时能够使用cout输出。

```cpp。

#include

using namespace std;。

struct Student 。

string name;。

int age;。

float score;。

friend ostream& operator<<(ostream &out, const Student &s) 。

out << "name: " << << ", age: " << << ", score:

" << ;。

return out;。

}。

};。

int main() 。

Student s = {"Tom", 18, 90};。

cout << s << endl; // 重载输出运算符,输出struct对象。

return 0;。

}。

```。

输出:

```。

name: Tom, age: 18, score: 90。

```。

2.重载输入运算符。

重载输入运算符可以使得在输入struct对象时能够使用cin输入。

```cpp。

#include

using namespace std;。

struct Student 。

string name;。

int age;。

float score;。

friend istream& operator>>(istream &in, Student &s) 。