第七章 运算符重载
一、填空题
1、在下列程序的空格处填上适当的字句,使输出为:0,2,10。
#include
#include
class Magic
{double x;
public:
Magic(double d=0.00):x(fabs(d))
{}
Magic operator+(_const Magic &c____)
{
return Magic(sqrt(x*x+c.x*c.x));
}
___Magic____operator<<(ostream & stream,const Magic & c)
{ stream<
}
};
int main()
{Magic ma;
cout<
二、编程题
1、 定义复数类的加法与减法,使之能够执行下列运算:
Complex a(2,5),b(7,8),c(0,0);
c=a+b;
c=4.1+a;
c=b+5.6;
#include
using namespace std;
class Complex
{
double m;
double n;
public:
Complex(double m = 0.0, double n = 0.0) : m(m),n(n){}
Complex operator+(const Complex &other) const
{
double m1 = m+ other.m;
double n1 = n + other.n;
return Complex(m1, n1);
}
};
int main()
{
Complex a(2, 5), b(7, 8), c(0, 0);
c = a + b;
cout << "c = " << c.m << " + " << c.n << endl;
c = 4.1 + a;
cout << "c = " << c.m << " + " << c.n << endl;
c = b + 5.6;
cout << "c = " << c.m << " + " << c.n << endl;
return 0;
}
2、 编写一个时间类,实现时间的加、减、读和输出。
class Time
{
int hour;
int min;
int sec;
public:
Time(int h,int m,int s):hour(h),min(m),sec(s){}
void readtime()
{cin >> hour >> min >> sec;}
void showtime()
{cout << hour << min << sec << endl;}
Time operator+(const Time &t)
{
int h=hours+t.hours;
int m=min+t.min;
int s=sec+t.sec;
if(s>=60)
{
m+=m/60;
s=s%60;
}
if(m>=60)
{
h+=h/60;
m=m%60;
}
if(h>24)
{
h=h%24;
}
return Time(h,m,s);
}
Time operator-(const Time &t)
{
int h=hours-t.hours;
int m=min-t.min;
int s=sec-t.sec;
if(s<0)
{
m-=1;
s+=60;
}
if(m<0)
{
h-=1;
m+=60;
}
if(h<0)
{
h+=24;
}
return Time(h,m,s);
}
};
3、 增加操作符,以允许人民币与double型数相乘。
friend money operator*(const money&,double);
friend money operator*(double,const money&);
注意:两个money对象不允许相乘。
class money
{
double num;
public:
friend money operator*(const money &m,double x);
friend money operator*(double y,const money &m);
};
money operator*(const money&m,double x)
{
money n;
n.num=m.num*x;
return n;
}
money operator*(double y,const money& m)
{
money n;
n.num=y*m.num;
return n;
}