继承与派生--习题

程序1:设计一个日期类Tdate,这个类包括以下成员:
(1) int型的数据成员year、month、day分别表示年月日;
(2) 根据需要定义构造函数
(3) 定义成员函数void display()实现日期的显示功能
设计一个学生类Student,这个类包括以下成员:
(1) string型的数据成员name表示姓名
(2) Tdate型的数据成员birthday表示生日
(3) char型的数据成员sex表示性别
(4) 根据需要定义构造函数
(5) 定义成员函数void display()实现学生信息的显示功能
编写测试程序对类的功能进行测试。

#include<iostream>
#include<string>
using namespace std;
class Tdate
{
protected:
	int year;
	int month;
	int day;
public:
	Tdate(int year,int month,int day)
	{
		this->year=year;
		this->month=month;
		this->day=day;
	}
	~Tdate(){}
	void display()
	{
		cout<<year<<"-"<<month<<"-"<<day;
	}
};
class Student
{
private:
	string name;
	Tdate birthday;
	char sex;
public:
	Student(string name,int year,int month,int day,char sex):birthday(year,month,day)
	{
		this->name=name;
		this->sex=sex;
	}
	~Student(){}
	void dispaly_S()
	{
		cout<<"name:"<<name<<endl;
		cout<<"sex:"<<sex<<endl;
		cout<<"birthday:";
		birthday.display();
		cout<<endl;
	}
};
int main()
{
	Student s("Ming",1998,12,12,'W');
	s.dispaly_S();
	return 0;
}

程序2:
1)定义日期的date类,其中包括数据成员年、月、日,要求包括构造函数;disp函数实现按“年/月/日”格式输出;重载“<”的运算符重载函数(日期较早者为小)。
2)建立date类的公有派生类Dtime,其中新增以下成员:时、分、秒;构造函数;
disp函数输出日期与时间;
在主函数中测试.

#include<iostream>
#include<string>
using namespace std;
class date
{
    protected:
    int year,month,day;
    public:
    date()
    {
        year=1990;
        month=1;
        day=1;
    }
    date(int year,int month,int day)
    {
        this->year=year;
        this->month=month;
        this->day=day;
    }
    ~date(){}
    void disp()
    {
        cout<<year<<"年/"<<month<<"月/"<<day<<"日";
    }
    bool operator<(date &d1)
    {
        if(year<d1.year)
        {
            return true;
        }else if(year==d1.year)
        {
            if(month<d1.month)
            {
                return true;
            }else if(month==d1.month)
            {
                if(day<d1.day)
                return true;
            }
        }
        return false;
    }
};
class Dtime:public date
{
    private:
    int hour,min,sec;
    public:
    Dtime(int year,int month,int day,int hour,int min,int sec)
    :date(year,month,day)
    {
        this->hour=hour;
        this->min=min;
        this->sec=sec;
    }
    ~Dtime(){}
    void dispT()
    {
        disp();
        cout<<hour<<":"<<min<<":"<<sec<<endl;
    }
};

int main()
{
    date d1(2020,3,4);
    date d2(2001,4,3);
    if(d1<d2)
    {
        d1.disp();
        cout<<"早于";
        d2.disp();
        cout<<endl;
    }else{
        d2.disp();
        cout<<"早于";
        d1.disp();
        cout<<endl;
    }
    Dtime t1(2010,2,3,12,0,0);
    t1.dispT();
    return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值