资源预览内容
第1页 / 共4页
第2页 / 共4页
第3页 / 共4页
第4页 / 共4页
亲,该文档总共4页全部预览完了,如果喜欢就下载吧!
资源描述
实验九 运算符重载(一)1、 实验目的理解运算符重载的概念和实质,掌握运算符重载函数的定义方法,掌握将运算符重载为类的成员函数和友元函数的方法,掌握和运用几种常用的用 C+语言运算符的重载进行解决问题的方法。2、 实验内容(1) 编写程序,运用运算符重载实现点类 Point 的两个对象(即两点)间横、纵坐标的相加运算。/ 1234.cpp : 定义控制台应用程序的入口点。/#include stdafx.h#include using namespace std;class pointpublic:point()x=0;y=0;point(int x1,int y1)x=x1;y=y1;point operator + (point void display();private:int x;int y;point point :operator + (point &p2)point p;p.x=x+p2.x;p.y=y+p2.y;return p;void point:display()coutusing namespace std;class Complexpublic:Complex()real=0;imag=0;Complex(double r,double i)real=r;imag=i;Complex operator*(Complex Complex operator/(Complex void display();private:double real;double imag;Complex Complex:operator*(Complex &c2)Complex c;c.real=real*c2.real-imag*c2.imag;c.imag=imag*c2.real+real*c2.imag;return c;Complex Complex:operator/(Complex &c2)Complex c;c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);return c;void Complex:display()coutusing namespace std;/(3) 设计一个长方形类Triangle,包含长和宽两个私有数据成员。要求重载运算符“+”,以实现多个矩形对象的面积之和。class rectangleprivate :int a,b;protected :int area;public:rectangle ()a=0,b=0,area=0;rectangle (int ra,int rb)a=ra;b=rb;area=ra*rb;rectangle operator+(rectangle void display();rectangle rectangle: operator+(rectangle &r2)rectangle r;r.area=area+r2.area ;return r;void rectangle :display()couta a b b area: areaendl;int main()rectangle t1(2,3), t2(3,5),t3;t3=t1+t2;t3.display ();return 0;实验小结
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号