做C++题的时候都不可避免的会遇到运算符重载的题:
举个例子:
在Rectangle.h中
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
int left,top,right,bottom;
public:
Rectangle(int l=0,int t=0,int r=0,int b=0);
void Assign(int l,int t,int r,int b);
void SetLeft(int t){left=t;}
void SetRight(int t){right=t;}
void SetTop(int t){top=t;}
void SetBottom(int t){bottom=t;}
void Show();
void operator +=(Rectangle &);
void operator -=(Rectangle &);
friend Rectangle operator +(Rectangle &,Rectangle &);
friend Rectangle operator -(Rectangle &,Rectangle &);
virtual ~Rectangle();
protected:
private:
};
#endif // RECTANGLE_H
在Rectangle.cpp中
#include "Rectangle.h"
#include <iostream>
using namespace std;
Rectangle::Rectangle(int l,int t,int r,int b)
{
left=l;right=r;top=t;bottom=b;
}
void Rectangle::Assign(int l,int t,int r,int b){
left=l;right=r;top=t;bottom=b;
}
void Rectangle::Show(){
cout<<"left-top point is("<<left<<","<<top<<")"<<endl;
cout<<"right-bottom point is("<<right<<","<<bottom<<")"<<endl;
}
void Rectangle::operator+=(Rectangle &rect){
int x=rect.right-rect.left;
int y=rect.bottom-rect.top;
right+=x;
bottom+=y;
}
void Rectangle::operator-=(Rectangle &rect){
int x=rect.right-rect.left;
int y=rect.bottom-rect.top;
right-=x;
bottom-=y;
}
Rectangle operator -(Rectangle &rect1,Rectangle &rect2){
rect1-=rect2;
return rect1;
}
Rectangle operator +(Rectangle &rect1,Rectangle &rect2){
rect1+=rect2;
return rect1;
}
Rectangle::~Rectangle()
{
//dtor
}
在main中
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main()
{
Rectangle rect;
cout<<"rect初始"<<endl;
rect.Show();
rect.Assign(100,200,300,400);
cout<<"rect Assign"<<endl;
rect.Show();
Rectangle rect1(0,0,200,200);
cout<<"rect1 Assign"<<endl;
rect1.Show();
rect+=rect1;
cout<<"与rect1相加"<<endl;
rect.Show();
Rectangle rect2;
rect2=rect1+rect;
cout<<"rect2(+)"<<endl;
rect.Show();
rect2=rect-rect1;
cout<<"rect2(-)"<<endl;
rect.Show();
return 0;
}
这样就解决了Rectangle的特殊定义的加减操作