This article is suitable for primary readers
Chuck Allison is a software architect at the Family History Research division of the Church of Christ, Salt Lake City St. Latter Day Church headquarters. He has a Bachelor of Mathematics and a master's degree in mathematics. He has been programming since 1975, and since 1984 he has been engaged in the teaching and development of C language. His current interest is in object-oriented technology and its education. He is a member of the X3j16,ansi C + + standardization committee. Send e-mail to allison@decus.org or call (801) 240-4510 to get in touch with him.
In last month's package I presented a prototype of a simple C + + date class. To provide a function that calculates the interval of two dates, this class illustrates the following characteristics of C + +:
inline function
Reference
Constructors
Access control for private data members
In this month's section I will add the associated operator, the input/output operation, and the ability to get the current date. They demonstrate the following characteristics:
Operator overloading
Flow
Friend function
Static members
When using a date you often need to determine whether a date is before another date. I will add the following member function for the date class (see Listing 1):
int compare(const Date& d2) const;
Date::compare is similar to strcmp-if the current object (*this) returns a negative integer before D2, it returns 0 if the two dates are the same, or returns a positive integer (see the function implementation in Listing 2 and the sample program in Listing 3). Like the qsort in the C standard library that you are all familiar with, you can also use Date::compare to sort the dates as if you were using strcmp to sort the strings. The following is a comparison function that can be passed to Qsort (the next month's code encapsulation will include Qsort):#include "date.h"
int datecmp(const void *p1, const void *p2)
{
const Date
*d1p = (const Date *) p1,
*d2p = (const Date *) p2;
return d1p->compare(*d2p);
}