c++ 设计一个类层次,基类为Date,从Date分别派生出ShortE、MediumDate和LongDate.他们各自有成员函数print(),输出当前日期。

  • Post author:
  • Post category:其他


设计一个类层次,基类为Date,从Date分别派生出ShortE、MediumDate和LongDate.他们各自有成员函数print(),输出当前日期。

Date输出日期格式为:04-14-2018

ShortE输出日期格式为:14-04-2018

MediumDate输出日期格式为:Apr.14,2018

LongDate输出日期格式为:April 14, 2018


class Date{


protected:


int year,month,day;


};

#include<iostream>
#include<ctime>
#include<string> 
using namespace std;
class Date{
    public:
         Date(){
             tm *t;
             time_t t1=time(0);
             t=localtime(&t1);
             year=t->tm_year+1900;
             month=t->tm_mon+1;
             day=t->tm_mday;    
    } 
    void print(){
         cout<<"Date:"<<month<<"--"<<day<<"--"<<year<<endl;
     } 
    protected:
        int year,month,day;     
};    
class ShortE:public Date{
    public:
        void print()
        {
            cout<<"ShortE:"<<day<<"--"<<month<<"--"<<year<<endl;
        }
};
class MediumDate:public Date{
 public:
   void print(){
    string a[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
    cout<<"MediumDate:"<<a[month-1]<<"."<<day<<","<<year<<endl;
    }           
};
class LongDate:public Date{
    public:
        void print(){
            string a[12]={"January ","February ","March ","April ","May ","June ",
            "July ","August ","September ","October ","November ","December "};
            cout<<"LongDate:"<<a[month-1]<<day<<","<<year<<endl;
        }        
};
int main()
{
    Date a;
    ShortE b;
    MediumDate c;
    LongDate d;
    a.print() ;
    b.print() ;
    c.print() ;
    d.print() ;

    return 0;
}



版权声明:本文为m0_73692754原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。