本文給出一個關於繼承性的綜合例子,該例子編寫一個有關日期(年、月、日)和時間(時、分、秒)的程序。該程序建立三個類,其中一個是日期的類Date,一個是時間的類Time,另一個是日期和時間類DateTime,它是前面兩個類為基類的派生類。
下面是該程序的源碼:
#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():Date() {}
TimeDate(int y, int mo, int d, int h, int mi, int s):Date(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:"< }
該程序中,對象的數據成員的值是通過成員函數獲取數據成員的字符串,然後再使用輸出語句進行輸出的。