第七章 运算符重载
一、填空题
1、在下列程序的空格处填上适当的字句,使输出为:0,2,10。
#include
#include
using namespace std;
class Magic{
double x;
public:
Magic(double d=0.00):x(fabs(d)){}
Magic operator+(const Magic &c)const{
return Magic(sqrt(x*x+c.x*c.x));
}
friend ostream &operator<<(ostream & stream,const Magic & c);
};
ostream &operator<<(ostream & cout,const Magic & c){
cout<<c.x;
return cout;
}
int main(){
Magic ma;
cout<<ma<<", "<<Magic(2)<<", "<<ma+Magic(-6)+Magic(-8)<
}
二、编程题
1、 定义复数类的加法与减法,使之能够执行下列运算:
Complex a(2,5),b(7,8),c(0,0);
c=a+b;
c=4.1+a;
c=b+5.6;
#include <iostream>
using namespace std;
class Complex{
private:
double x;
double y;
public:
Complex(double a,double b):x(a),y(b){}
void show(){
cout << "(" << x << "," << y << ")" << endl;
}
friend Complex & operator+(Complex &c1,Complex &c2);
friend Complex & operator+(double c1,Complex &c2);
friend Complex & operator+(Complex &c1,double c2);
};
Complex & operator+(Complex &c1,Complex &c2){
c1.x+=c2.x;
c1.y+=c2.y;
return c1;
}
Complex & operator+(double c1,Complex &c2){
c2.x+=c1;
return c2;
}
Complex & operator+(Complex &c1,double c2){
c1.x+=c2;
return c1;
}
int main(){
Complex c1(1.2,3.67);
Complex c2(2.3,4.89);
Complex c3=c1+c2;
c3.show();
Complex c4=c1+2;
c4.show();
Complex c5=3+c2;
c5.show();
}
#include <iostream>
using namespace std;
class MyTime{
private:
int hour;
int min;
int sec;
public:
MyTime(int h,int m,int s):hour(h),min(m),sec(s){}
friend MyTime & operator+(MyTime & mt1, MyTime & mt2);
void show(){
cout << hour << ":" << min << ":" << sec << endl;
}
};
MyTime & operator+(MyTime & mt1, MyTime & mt2){
int secToMin=0;
if(mt1.sec+mt2.sec>=60){
mt1.sec=(mt1.sec+mt2.sec)%60;
secToMin=1;
}
int minToHour=0;
if(mt1.min+mt2.min+secToMin>=60){
mt1.min=(mt1.min+mt2.min+secToMin)%60;
minToHour=1;
}
mt1.hour=mt1.hour+mt2.hour+minToHour;
return mt1;
}
int main(){
MyTime mt1(3,15,27);
MyTime mt2(4,45,47);
MyTime mt3(22,55,47);
MyTime mt4=mt1+mt2;
mt4.show();
MyTime mt5=mt2+mt3;
mt5.show();
return 0;
}
3、 增加操作符,以允许人民币与double型数相乘。
friend money operator*(const money&,double);
friend money operator*(double,const money&);
注意:两个money对象不允许相乘。
#include <iostream>
using namespace std;
class Money{
private:
int yuan;
int jiao;
int fen;
public:
Money(int y=0, int j=0, int f=0):yuan(y),jiao(j),fen(f){}
void show(){
cout << yuan << "元" << jiao << "角" << fen << "分" << endl;
}
friend Money operator*(Money &m, double d);
friend Money operator*(double d, Money &m);
};
Money operator*(Money &m, double d){
double md=(m.yuan+0.1*m.jiao+0.01*m.fen)*d;
Money rm;
rm.yuan=int(md);
rm.jiao=(int(md*10))%10;
rm.fen=(int(md*100))%10;
return rm;
}
Money operator*(double d,Money &m){
double md=(m.yuan+0.1*m.jiao+0.01*m.fen)*d;
Money rm;
rm.yuan=int(md);
rm.jiao=(int(md*10))%10;
rm.fen=(int(md*100))%10;
return rm;
}
int main(){
Money m1(123,5,8);
Money m2=m1*1.5;
m2.show();
Money m3=m1*1.24;
m3.show();
return 0;
}