重载运算符学习

本文介绍了一个C++程序示例,展示了如何通过重载运算符实现矩形类的各种操作,包括输入输出流的重载、加法运算符重载及比较运算符的重载等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<pre name="code" class="cpp">/***************************************/
重载运算符的学习2015年8月
/**************************************/
#include <iostream>
using namespace std;
class ApRect{
public:
	//
	ApRect(){}
	ApRect(double ht,double wid){height=ht;width=wid;}
	//
	double Area(){return height*width;}
	double Width(){return width;}
	double Height(){return height;}
	//
	friend istream& operator >>(istream& in,ApRect& cls);
	//
	friend ostream& operator <<(ostream& out,ApRect& cls);
	//
	double operator + (const ApRect rect);
	//
	double operator [] (const int index);
	//
	friend bool operator > (ApRect rect_1, ApRect rect_2_);
	bool operator < (ApRect rect);

	//
	~ApRect(){}
private:
	double height;
	double width;
};
istream& operator >> (istream& in, ApRect& cls){
	cout<<"input height and width:";
	in>>cls.height>>cls.width;
	return in;
}

ostream& operator <<(ostream& out, ApRect& cls){
	out<<"height:"<<cls.height<<";width:"<<cls.width;
	return out;
}
double ApRect::operator +(ApRect rect){
	return Area()-rect.Area();
}
double ApRect::operator [](int a){
	switch(a){
		case 0:
			return Height();break;
		case 1:
			return Width();break;
		case 2:
			return Area();break;
		default:
			return 0.0;break;
	}
}
bool operator >(ApRect rect_1,ApRect rect_2){
	return (rect_1.Area()>rect_2.Area()) ? true:false;
}
bool ApRect::operator <(ApRect rect){
	return (Area()<rect.Area()) ? true:false;
}

int main(){
ApRect rect_1;
ApRect rect_2(10,20);
cin>>rect_1;
cout<<endl<<"rect_1"<<rect_1<<endl;
cout<<"rect_2:"<<rect_2<<endl<<endl;	
//add
cout<<"+:"<<rect_1+rect_2<<endl;
return 0;
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值