第四周学习:流插入和流提取运算符重载

cout<<5<<"this" 本质为
cout.operator<<(5) . operator<<("this")
连着两次operator<<(),说明前面一部分返回的是cout&.
又因为ostream类早就写好了,所以不可能写成成员函数,所以写成friend函数or global函数。

#include<iostream>
#include<string>
using namespace std;
class T
{
    
    
	private:
		int age;
		string name;
	public:
		T(int n=0,string str="no"):age(n),name(str){
    
    }
		friend ostream& operator<<(ostream& os,const T& t)
		{
    
    
			os<<t.name<<" is "<<t.age<<" years old"<<endl;
			return os;
		}
		
		friend istream& operator>>(istream& is,T& t)
		{
    
    
			is>>t.name;
			is>>t.age;
			return is;
		}
 } ;
 
 int main()
 {
    
    
 	T t1(20,"Jeff"),t2(19,"Fuck");
 	cout<<t1<<t2;
 	cin>>t2;
 	cout<<t2;
 }

<<重载运算符因为不改变类对象,所以用常量参数来表示类对象。
/>>重载运算符因为要改变类对象,所以不能用const
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108570564