一、填空题
1、在下列程序的空格处填上适当的字句,使输出为:0,2,10。
#include <iostream>
#include <math.h>
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<<c.x;
return stream;
}
};
int main()
{Magic ma;
cout<<ma<<", "<<Magic(2)<<", "<<ma+Magic(-6)+
Magic(-8)<<endl;
}
二、编程题
1、 定义复数类的加法与减法,使之能够执行下列运算:
Complex a(2,5),b(7,8),c(0,0);
c=a+b;
c=4.1+a;
c=b+5.6;
#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator+(double num) const {
return Complex(real + num, imag);
}
Complex operator-(double num) const {
return Complex(real - num, imag);
}
friend Complex operator+(double num, const Complex& c) {
return Complex(num + c.real, c.imag);
}
friend Complex operator-(double num, const Complex& c) {
return Complex(num - c.real, -c.imag);
}
void display() const {
std::cout << "(" << real << ", " << imag << ")" << std::endl;
}
};
int main() {
Complex a(2, 5), b(7, 8), c(0, 0);
c = a + b;
c.display(); // 输出:(9, 13)
c = 4.1 + a;
c.display(); // 输出:(6.1, 5)
c = b + 5.6;
c.display(); // 输出:(12.6, 8)
return 0;
}
2、 编写一个时间类,实现时间的加、减、读和输出。
#include"iostream"
using namespace std;
class Time
{
public:
Time(int h=0,int m=0,int s=0):hour(h),minute(m),second(s){}
void SetTime(int,int,int);
Time operator + (Time &a);
Time operator - (Time &a);
friend istream & operator >>(istream&,Time&);
friend ostream & operator <<(ostream&,Time&);
private:
int hour,minute,second;
};
void Time::SetTime(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
Time Time::operator + (Time &a)
{
return Time(hour+a.hour,minute+a.minute,second+a.second);
}
Time Time::operator - (Time &a)
{
return Time(hour-a.hour,minute-a.minute,second-a.second);
}
istream & operator >>(istream&is,Time&a)
{
is>>a.hour>>a.minute>>a.second;
return is;
}
ostream & operator <<(ostream&os,Time&b)
{
os<<b.hour<<'/'<<b.minute<<'/'<<b.second<<endl;
return os;
}
int main()
{
Time a,b,c;
cout<<"请输入A的时间:"<<endl;
cin>>a;
cout<<"请输入B的时间:"<<endl;
cin>>b;
cout<<"A的时间为:";
cout<<a;
cout<<"B的时间为:";
cout<<b;
cout<<"c=a+b=";
c=a+b;
cout<<c;
cout<<endl<<"c=a-b=";
c=a-b;
cout<<c;
return 0;
}
3、 增加操作符,以允许人民币与double型数相乘。
friend money operator*(const money&,double);
friend money operator*(double,const money&);
注意:两个money对象不允许相乘。