C + + can use stream extraction operators >> and stream insert operators << to enter and output built-in data types. We can overload the stream extraction operator and the stream insert operator to manipulate user-defined data types such as objects.
Here, it is important to declare the operator overload function as a friend function of the class, so that we can directly invoke the function without creating the object.
The following example shows how to overload the extract operator >> and insert operator <<.
#include <iostream>using namespace std;class Person{public: Person(const char *str) : name(str){} int GetAge(){ return this->age; } /* 声明为类的友元函数 */ friend ostream& operator<<(ostream& output, Person &p){ output << p.name << endl; return output; } friend istream& operator>>(istream& input, Person &p){ input >> p.age; return input; } private: const char *name; int age;};int main(){ Person p("Tom"); /* 重载输出名字 */ cout << p; /* 重载输入年龄 */ cin >> p; /* 输出年龄 */ cout << p.GetAge() << endl; return 0;}
C + + input, output operator overloading