C++ 输入、输出运算符重载

C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。我们可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。

在这里,有一点很重要,我们需要把运算符重载函数声明为类的友元函数,这样我们就能不用创建对象而直接调用函数。
下面的实例演示了如何重载提取运算符 >> 和插入运算符 <<。

#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;
}
原文地址:https://www.cnblogs.com/GyForever1004/p/8476644.html