第七章 运算符重载
一、填空题
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));
}
_ostream operator<<(ostream & stream,const Magic & c)
{ stream<
return stream;
}
};
int main()
{Magic ma;
cout<
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
using namespace std;
class Complex
{
friend class Constant;
private:
double x;
double y;
public:
Complex(double x=0,double y=0):x(x),y(y)
{}
const Complex operator+(const Complex &c) const
{
Complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return temp;
}
const Complex operator+(const double x) const
{
Complex temp;
temp.x=this->x+x;
temp.y=y;
return temp;
}
void show()
{
cout << x << " " << y << endl;
}
};
class Constant
{
private:
double x;
public:
Constant(double x=0):x(x)
{}
const Complex operator+(const Complex &c) const
{
Complex temp;
temp.x=x+c.x;
temp.y=x+c.y;
return temp;
}
};
int main()
{
Complex a(2,5);
Complex b(7,8);
Complex c;
Constant d(4.1);
c=a+b;
c.show();
c=d+a;
c.show();
c=b+5.6;
c.show();
return 0;
}
2、 编写一个时间类,实现时间的加、减、读和输出。
#include
using namespace std;
class Time
{
private:
int hour;
int min;
int sec;
public:
Time(int hour=0,int min=0,int sec=0):hour(hour),min(min),sec(sec)
{}
const Time operator+(const Time &t) const
{
Time temp;
int flag=0;
temp.sec=sec+t.sec;
if(temp.sec>=60)
{
flag=1;
temp.sec-=60;
}
temp.min=min+t.min;
if(flag==1)
{
temp.min++;
}
if(temp.min>=60)
{
flag=2;
temp.min-=60;
}
temp.hour=hour+t.hour;
if(flag==2)
{
temp.hour++;
}
if(temp.hour>=24)
{
temp.hour-=24;
}
return temp;
}
const Time operator-(const Time &t) const
{
Time temp;
int flag=0;
temp.sec=sec-t.sec;
if(temp.sec<0)
{
flag=1;
temp.sec+=60;
}
temp.min=min-t.min;
if(flag==1)
{
temp.min--;
}
if(temp.min<0)
{
flag=2;
temp.min+=60;
}
temp.hour=hour-t.hour;
if(flag==2)
{
temp.hour--;
}
if(temp.hour<0)
{
temp.hour+=24;
}
return temp;
}
void show()
{
cout << hour << " : " << min << " : " << sec << endl;
}
};
int main()
{
Time t1(22,51,33);
Time t2(15,44,55);
Time t3=t1+t2;
t3.show();
Time t4=t2-t1;
t4.show();
return 0;
}
3、 增加操作符,以允许人民币与double型数相乘。
friend money operator*(const money&,double);
friend money operator*(double,const money&);
注意:两个money对象不允许相乘。
#include
using namespace std;
class Money {
private:
double amount;
public:
Money(double amt = 0.0) : amount(amt) {}
friend Money operator*(const Money& money, double num) {
return Money(money.amount * num);
}
friend Money operator*(double num, const Money& money) {
return Money(money.amount * num);
}
};