C + + Inheritance application Example: Date and time

Source: Internet
Author: User
Tags date1 inheritance sprintf

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.