程序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;
}