欢迎来到天天文库
浏览记录
ID:9182223
大小:202.57 KB
页数:8页
时间:2018-04-20
《实验二 运算符重载》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、XbC++实验2实验二运算符重载班级电子信息工程1班学号Xb姓名汪丽娟1.实验目的:(1)学习定义和使用重载运算符。(2)熟悉拷贝构造函数。2.实验任务:(1)对比通过函数来实现复数相加和通过重载运算符实现复数相加的不同之处(2)定义一个有理数类Rational,包含分子和分母两个属性,为其重载四则运算和输入输出流,以使用cin和cout对Rational的对象进行输入和输出。(3)定义RMB类,数据成员有yuan、jf,请为该类定义构造函数、并重载“+”、“-”、“<<”、“>>”。选做:定义账户类,有账号、户名、余额等属性,具有存
2、款、取款等操作,可以把RMB类对象作为成员,进行存取款操作。(4)若有如下类,请重载赋值运算符,解决指针悬挂的问题.3.设计思路:(1)通过函数来实现复数相加时是在Complex类外定义一个Complex类的成员函数Complex_add。而通过重载运算符实现复数相加是运用了“函数operator+重载了运算符+”。在执行复数相加时的表达式c1+c2时,系统会调用operator+函数,把c1和c2作为实参,与形参进行虚实结合。(2)用了友元函数实现输入输出,定义Rational类使用构造函数来实现调用。重载运算符实现加减。(3)用了
3、友元函数实现输入输出,定义RMB类使用构造函数来实现调用。重载运算符实现加减。4.列出代码:任务一:通过函数来实现复数相加8XbC++实验2#includeclassComplex{public:Complex(){real=0;imag=0;}8XbC++实验2Complex(doubler,doublei){real=r;imag=i;}Complexcomplex_add(Complex&c2);voiddisplay();private:doublereal;doubleimag;};ComplexCo
4、mplex::complex_add(Complex&c2){Complexc;c.real=real+c2.real;c.imag=imag+c2.imag;returnc;}voidComplex::display(){cout<<"("<5、1+c2=";c3.display();return0;}通过重载运算符实现复数相加#includeclassComplex{public:Complex(){real=0;imag=0;}Complex(doubler,doublei){real=r;imag=i;}Complexoperator+(Complex&c2);voiddisplay();private:doublereal;doubleimag;};ComplexComplex::operator+(Complex&c2){Complexc;c6、.real=real+c2.real;c.imag=imag+c2.imag;returnc;}voidComplex::display(){cout<<"("<7、tream>#include#includeusingnamespacestd;classRational{private:intnumberator;intdenominator;intGcd(intp,intq);public:Rational();Rational(inta,intb);voidset(inta,intb);voidPrint();RationalAdd(Rationala);voidDiv(Rationala);RationalSub(Rationala);RationalMul(8、Rationala);};Rational::Rational(){numberator=1;denominator=1;}Rational::Rational(inta,intb){numberator=a;denom
5、1+c2=";c3.display();return0;}通过重载运算符实现复数相加#includeclassComplex{public:Complex(){real=0;imag=0;}Complex(doubler,doublei){real=r;imag=i;}Complexoperator+(Complex&c2);voiddisplay();private:doublereal;doubleimag;};ComplexComplex::operator+(Complex&c2){Complexc;c
6、.real=real+c2.real;c.imag=imag+c2.imag;returnc;}voidComplex::display(){cout<<"("<7、tream>#include#includeusingnamespacestd;classRational{private:intnumberator;intdenominator;intGcd(intp,intq);public:Rational();Rational(inta,intb);voidset(inta,intb);voidPrint();RationalAdd(Rationala);voidDiv(Rationala);RationalSub(Rationala);RationalMul(8、Rationala);};Rational::Rational(){numberator=1;denominator=1;}Rational::Rational(inta,intb){numberator=a;denom
7、tream>#include#includeusingnamespacestd;classRational{private:intnumberator;intdenominator;intGcd(intp,intq);public:Rational();Rational(inta,intb);voidset(inta,intb);voidPrint();RationalAdd(Rationala);voidDiv(Rationala);RationalSub(Rationala);RationalMul(
8、Rationala);};Rational::Rational(){numberator=1;denominator=1;}Rational::Rational(inta,intb){numberator=a;denom
此文档下载收益归作者所有