A C + + Date class (first part)

Source: Internet
Author: User
Tags constructor exception handling function prototype inheritance

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.

Last month's column introduced a date-interval function that can calculate the year, month, and day between any two dates. This month's column presents a way to solve the problem in C + +. The essence of this approach is to create a new type of data that behaves like a built-in data type. In other words, you want to switch from a functional approach ("How do I want to do things") to an object-based approach ("What's the principle and object of my question"). Using C + + requires another way to think about problems. To implement this transformation, you first need to know why C + + exists.

Stories about the two languages

C + + originated in the early 80 's at&t Bjarne Stroustrup proposed "with Class C". He was looking for a quicker way to simulate in Simula-67. "Class" is the term used in Simula to refer to the type defined by the user, and can define objects that are very close to reality, which is the key to good emulation. Is there a better way to simulate faster than adding "class" to the C language, the fastest process language?

Select C provides a useful and flexible tool for the class. Although some other languages have long supported the abstraction of data through classes, they are most widely used in C + +. Almost every major platform with a C-language compiler can also support C + +. Finally, I've also heard that C + + user groups will double every seven months.

The initial understanding of C + + is astonishing. If you are transferring from C, you need to add the following words to your vocabulary: abstract class, access control, base class, catch clause, class, Scope of class, constructor, copy constructor, default parameter, default constructor, delete operator, derived class, destructor, exception, exception handling , friends, inheritance, inline functions, operators, member functions, multiple inheritance, nested classes, new handler functions, new operator, overload, member pointer, polymorphic, private, protected, public, pure virtual function, reference, static member, stream, template, this pointer, try block, type safe connection, virtual base class, virtual function.

The good news is that C + + is a powerful, effective, object-oriented language that can handle a variety of complex applications. The bad news is that the language itself is more complex and difficult to master than the C language. C language is part of the problem. C + + is a half-breed, which features both object-oriented and universal system programming languages. We can not simply introduce C + + This series of rich new features without taking into account the C language itself. Compatibility with C is a major goal in C + + design. As Bjarne stated in the ANSI C + + committee, C + + is an "engineering compromise" that "wants to be as close to the C language as possible, but not too close". How close to the present is still under study.

A gradual process.

You can use C + + effectively without having to master all of it. In fact, object-oriented technology promises that as long as developers do their thing (providing well-designed, reusable and scalable class libraries), you can easily develop your applications. Current products, such as the Borland Company's application programming interface, are proving this in many ways.

If you feel you have to master the language, you can step in and continue to develop your application in the process. Here are three places to master:

A better C language

Data abstraction

Object-Oriented Programming

You can use C + + as a better C language, because it is more secure and more expressive. The features associated with this are: type-safe connections, mandatory function prototypes, inline functions, const qualifiers (yes, ANSI C from C + +), function overloading, default parameters, references, and language-provided support for dynamic memory management. You also need to be careful where these two languages are incompatible. C has a powerful subset, plum and Saks call it "type-safe C" (see C + + programming guidelines, plum and Saks, Plum-hall, 1992).

As I stated in this post and in the next article, C + + supports data abstraction--users can define data types that behave like built-in types, including classes, access restrictions, construction and destructor functions, operator overloading, templates, and exception handling.

Object-oriented programming is designed to further the data abstraction by exploring the relationship between classes and class. Two of the key concepts are inheritance (by declaring a new class similar to another class and distinguishing it, where the similarity is reused) and polymorphism (providing the same interface for a family-related operation, runtime recognition). C + + supports inheritance and polymorphism, respectively, through the derivation of classes and the number of sweating.

Class

A class is an extended struct. In addition to defining data members, you can also add member functions to them. The definition of a date class is Listing 1 in the file data.h. It's different from the C version of last month, because here the interval function is a member function rather than a global function. The implementation of Date::interval () is in Listing 2. ':: ' is called the scope operator. It tells the compiler that the interval function is a member function of the date class. The "&" in the interval function prototype indicates that the parameters of this function are passed by the application (see the options for references). The program in Listing 3 shows how to use this date class. You must use the syntax of the struct member to call Date:: Interval ():

result = d1.interval (d2);

Date acts as a type identifier, just as a system-built type does (for example, you can define an object of date without using the struct keyword). You never have to do the following definitions:

typedef struct Date Date;

In fact, the concept of a class is so fundamental that C + + has incorporated the structure tag into a separate namespace with the generic identifier.

Note that I have defined isleap as an inline function (it is a macro in the C version). An inline function expands the code like a macro, but it also checks for the threshold and type of action like a normal function. Unless you want to use the stringizing or token-pasting operations of the preprocessor, you do not need to use Function-like macros in C + +. Now consider this statement in Listing 2:

years = d2.year - year;

What is the object of year? In the C version, this statement is as follows:

years = d2.year - d1.year;

Since the invocation of a member function is always associated with an object (for example, D1. Interval (D2)), so when a member function has no prefix modification, it is usually a member of the associated object (here, year refers to D1.year). The This keyword represents a pointer to a potential object, so I can make a clearer statement:

years = d2.year - this->year;But this usage is very small. In Listing 4, I added the following declaration to the definition of the class:Date();
Date(int,int,int);

This is a special member function called a constructor. The constructor allows you to specify how the object is initialized when an object is created. When you define a Date object that has no initial value, the default constructor is called first (because it has no arguments):

Date d;The following declaration calls the second constructor:

Date d(10,1,51);

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.