设为首页 加入收藏

TOP

C++继承性应用实例日期和时间
2014-11-23 19:57:22 】 浏览:210
Tags:继承性 应用 实例 日期 时间

  本文给出一个关于继承性的综合例子,该例子编写一个有关日期(年、月、日)和时间(时、分、秒)的程序。该程序建立三个类,其中一个是日期的类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:"< }


该程序中,对象的数据成员的值是通过成员函数获取数据成员的字符串,然后再使用输出语句进行输出的。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇利用PDFLib生成PDF文档 下一篇C++语言代码检查工具PC-Lint简介

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目