十、C++运算符重载
来源:互联网 发布:linux apache ab测试 编辑:程序博客网 时间:2024/06/05 20:18
做C++题的时候都不可避免的会遇到运算符重载的题:
举个例子:
在Rectangle.h中#ifndef RECTANGLE_H#define RECTANGLE_Hclass 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的特殊定义的加减操作
阅读全文
0 0
- 十、C++运算符重载
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- [C++]运算符重载
- 【c++】运算符重载
- C++:运算符重载
- C#:运算符重载
- Ijikplayer视频播放的简单使用
- CFF 1016 计算天数
- 学生管理系统
- 深度学习对训练样本的数量要求
- [BZOJ4241]-历史研究-回滚莫队
- 十、C++运算符重载
- 六度空间
- 怎么销毁一个Activity,点击按钮退出activity
- 贪心算法--圣诞老人的礼物(openjudge 4110 )
- 如何使用call和apply
- TF-IDF算法
- java 死锁及解决
- Neural Talk简介
- 神经网络的神奇之处