年假作业6

一、填空

1、0,2,10

二、编程

1、

#include 
using namespace std;
class Complex
{
private:
    double real;//实部
    double imag;//虚部
public:
    //有参构造函数
    Complex(double r, double i):real(r), imag(i){}
    //复数加法运算符重载
    Complex operator+(const Complex &other)const
    {
        return Complex(real+other.real,imag+other.imag);
    }
    //复数与实数加法运算符重载
    Complex operator+(double s)const
    {
        return Complex(real+s,imag);
    }
    //实数与复数加法运算符重载
    friend Complex operator+(double s,const Complex &c);
    //复数减法运算符重载
    Complex operator-(const Complex &other)const
    {
        return Complex(real-other.real,imag-other.imag);
    }
    //输出复数
    void show()const
    {
        cout << "(" << real << ", " << imag << ")" << endl;
    }
};
//实数与复数加法运算符重载的实现
Complex operator+(double s, const Complex &c)
{
    return Complex(s+c.real,c.imag);
}
int main()
{
    Complex a(4,3);
    Complex b(2,6);
    Complex c(0,0);
    c=a+b;
    c.show();
    c=4.1+a;
    c.show();
    c=b+5.6;
    c.show();
    return 0;
}

年假作业6_第1张图片

2、

#include 
#include 
using namespace std;
class Time
{
private:
    int hours;  //小时
    int minutes;  //分钟
    int seconds;  //秒
public:
    //构造函数
    Time(int h,int m,int s):hours(h),minutes(m),seconds(s){}
    //加法操作
    Time operator+(const Time &other)const
    {
        int total_seconds=seconds+other.seconds+60*(minutes+other.minutes)+3600*(hours+other.hours);
        int new_seconds=total_seconds%60;
        int new_minutes=(total_seconds/60)%60;
        int new_hours=total_seconds/3600;
        return Time(new_hours,new_minutes,new_seconds);
    }
    //减法操作
    Time operator-(const Time &other)const
    {
        int total_seconds=seconds-other.seconds+60*(minutes-other.minutes)+3600*(hours-other.hours);
        if(total_seconds<0)
        {
            total_seconds+=3600*24;//如果小于0,借一天
        }
        int new_seconds=total_seconds%60;
        int new_minutes=(total_seconds/60)%60;
        int new_hours=total_seconds/3600;
        return Time(new_hours,new_minutes,new_seconds);
    }
    //读取时间
    void setTime(int h,int m,int s)
    {
        hours=h;
        minutes=m;
        seconds=s;
    }
    //输出时间
    void show()const
    {
        cout << hours << ":" << minutes << ":" << seconds << endl;
    }
};
int main()
{
    Time t1(14,25,13);
    Time t2(3,12,23);
    //加法
    Time t3=t1+t2;
    cout << "t1+t2=";
    t3.show();
    //减法
    Time t4=t1-t2;
    cout << "t1-t2=";
    t4.show();
    //读取时间
    t1.setTime(15,30,0);
    cout << "Set t1 to ";
    t1.show();
    return 0;
}

年假作业6_第2张图片

3、不会

你可能感兴趣的:(c++,开发语言)