C++类的友元函数

#include<iostream>
#include<iterator>
#include<set>
using namespace std;
class Rect
{
private:
	int no;
	int width;
	int height;
public:
	Rect(int n=0,int w=0,int h=0);
	//定义为友元函数的原因是因为只有友元函数与成员函数才能访问类的私有成员
	friend bool operator<(const Rect &a,const Rect &b);//运算符重载,用于排序 
	friend istream& operator>>(istream &is,Rect &r);//输入一个对象
	friend ostream& operator<<(ostream &os,const Rect& r);//输出一个对象
};
int main()
{
	set<Rect> SR;
	int m,n;
	cin>>m;
	while(m--)
	{
		SR.clear();
		Rect R;
		cin>>n;
		for(int i=0;i<n;i++)
		{
			cin>>R;
			SR.insert(R);
		}
		cout<<endl;
		copy(SR.begin(),SR.end(),ostream_iterator<Rect>(cout,"\n"));
	}
	return 0;
}
Rect::Rect(int n,int w,int h)
{
	no=n;
	width=w;
	height=h;
}

bool operator<(const Rect &a,const Rect &b)//注意友元函数不是类的成员,所以不能使用::限定符
{
	return a.no<b.no||(a.no==b.no&&a.height<b.height)||(a.no==b.no&&a.height==b.height&&a.width<b.width);
}
istream& operator>>(istream &is,Rect& r)
{
	is>>r.no>>r.height>>r.width;
	if(r.height<r.width)
	{
		int temp=r.height;
		r.height=r.width;
		r.width=temp;
	}
	return is;
}

ostream& operator<<(ostream &os,const Rect& r)
{
	os<<r.no<<" "<<r.height<<" "<<r.width;
	return os;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值