十、C++运算符重载

做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的特殊定义的加减操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值