This article gives a comprehensive example of inheritance, which compiles a program about dates (year, month, day) and time (time, minutes, seconds). The program establishes three classes, one of which is the date class date, one is the time class times, and the other is the date and Time class DateTime, which is a derived class of the preceding two classes as the base class.
The following is the program's source code:
#include
#include
#include
typedef char STRING80[80];
Class Date
{
Public
Date () {}
Date (int y, int m, int d) {setdate (Y, M, d);}
void setdate (int y, int m, int d)
{
Year = y;
Month = m;
Day = D;
}
void Getstringdate (String80 &date)
{
sprintf (Date, "%d/%d/%d", year, Month, day);
}
Protected
int year, Month, day;
};
Class time
{
Public
Time () {}
Time (int h, int m, int s) {settime (H, M, s);}
void settime (int h, int m, int s)
{
Hours = h;
Minutes = m;
Seconds = s;
}
void Getstringtime (String80 &time)
{
sprintf (Time, "%d:%d:%d", Hours, Minutes, Seconds);
}
Protected
int Hours, Minutes, Seconds;
};
Class Timedate:public Date, public time
{
Public
Timedate ():D ate () {}
timedate (int y, int mo, int d, int h, int mi, int s):D ate (y, MO, D), Time (H, MI, s) {}
void Getstringdt (String80 &dtstr)
{
sprintf (Dtstr, "%d/%d/%d;%d:%d:%d", year, Month, Day, Hours, Minutes, Seconds);
}
};
void Main ()
{
Timedate Date1, Date2 (1998, 8, 12, 12, 45, 10);
String80 Demostr;
Date1. Setdate (1998, 8, 7);
Date1. SetTime (10, 30, 45);
Date1. GETSTRINGDT (DEMOSTR);
cout<< "The Date1 date and time is:" < date1. Getstringdate (DEMOSTR);
cout<< "The Date1 date is:" < date1. Getstringtime (DEMOSTR);
cout<< "The Date1 Time is:" < Date2. GETSTRINGDT (DEMOSTR);
cout<< "The Date2 date and time is:" <}
In this program, the value of the data member of an object is a string of data members obtained by a member function, which is then output using the output statement.