Polymorphism in Object-Oriented Programming Language C ++

Source: Internet
Author: User

Polymorphism in Object-Oriented Programming Language C ++

C ++ is a C language that supports data abstraction and object-oriented programming languages. C ++ draws on the C language extensions

The best features of many famous languages, such as the operator overload mechanism learned from algo168. Because c ++ has

High execution efficiency, and easy to be accepted by software personnel familiar with C language, so it quickly became popular. However, this hybrid object-oriented

The programming language is a new programming language, and many potential performances (encapsulation, inheritance, polymorphism, etc.) of it are not yet adequate.

Understanding and application did not give full play to its advantages. Polymorphism is one of the important concepts of object oriented systems. It refers to the same message.

Objects that can be sent to the parent class and its subclass. This article focuses on the application of polymorphism in programming.

1. Implementation form of Polymorphism

Broadly speaking, polymorphism refers to the ability of a program to process multiple types of objects. In C ++, this polymorphism can be

It is implemented by four forms: Forced polymorphism, heavy load polymorphism, type parameterized polymorphism, and inclusion polymorphism. Type parameterized polymorphism and inclusion Polymorphism

It is called General polymorphism and is used to systematically portray a group of semantic-related types. Heavy-load polymorphism and forced polymorphism are collectively referred to as special polymorphism,

It is used to depict the relationship between non-correlated types in semantics.
The inclusion polymorphism refers to the sub-typeization. A program segment can process both objects of the type T and the child type s of the type T.

This section is called a multi-state section. Public inheritance can implement subtypes. In the inclusion polymorphism, an object can be considered as a non-

For the same class, the existence of contained relationships means the existence of public structures. Contains polymorphism in many languages, such as the integer type

A subset constitutes a subtype. Objects in each child type can be used in a higher-level type, and all operations in a higher-level type can be

Used for objects at the next level. In C ++, the public inheritance relationship is a type of inclusion polymorphism. Each class can directly inherit the parent class or multiple parent classes.

Class, such as the statement class dpublic P1, public P2 {......}; Indicates that Class D is the child type of class P1 and class P2 respectively.
Type parameterized polymorphism means that when a function (class) uniformly operates on several types of parameters, these types indicate some common languages.

This function (class) is used to describe this feature. In type parameterized polymorphism, one polymorphism function (class) must contain at least

1 type parameter, which determines the type of the operand of a function (class) during each execution. This type of function (class) is also called a class function (class)

. Type parameterized polymorphism is widely used and called the most pure polymorphism.
Overload refers to the use of the same name to name different functions or operators. Function overload is the operator weight in C ++ for general programming languages.

Expansion of the load mechanism, which allows functions with the same or similar meanings to use the same name, as long as the number, order, or type of the parameters are not

. For example:
Int min (int x, int y); // returns the minimum number of two integers.
Int min (int x, int y, int Z); // returns the minimum number of three integers.
Int min (int n, int A []); // calculates the minimum number of N integers.
When you want to increase the function of comparing two strings, you only need to add:

Char * min (char *, char *);

In the past, the logic of how to use this set of functions does not need to be changed. The min function is easy to expand, that is, the maintenance is easy.

Higher program comprehensibility, "min" indicates the function for minimum value.
Forced refers to the semantic operation that converts a value of one type to another type to prevent type errors. Type conversion

It can be implicit and completed during compilation. For example, the statement d = I converts the integer variable to the real type. It can also be explicit and can be dynamically run.

.
In general, General polymorphism is true polymorphism, and special polymorphism is only the surface polymorphism. Because the overload only allows

A symbol has multiple types, and its values have different incompatible types. Similarly, implicit type conversion is also

Not true polymorphism, because each value must be converted to the required type before the operation starts, and the output type is also irrelevant to the input type.

In contrast, subclass and inheritance are truly polymorphism. Type parameterized polymorphism is also a pure polymorphism. The same object or function is not

The same type is used in the context without implicit type conversion, runtime detection, or other restrictions.

2. polymorphism Application

2.1 inclusion Polymorphism
C ++ uses virtual functions to implement inclusion polymorphism. virtual functions provide a more flexible polymorphism mechanism for C ++.

The virtual functions are the essence of polymorphism. Classes containing at least one virtual function are called polymorphism classes. Contains many

Mode is frequently used in programming.
The derived class inherits all operations of the Base class, or the operation of the Base class can be used to operate the objects of the derived class. When the operation of the Base class is not

To adapt to a derived class, the derived class must reload the operation of the Base class. For details, see void circle: showarea () in the following example ().
# Include <iostream. h>
Class Point // The dot class on the screen
{Int X, Y;
Public;
Point (INT X1, int Y1)
{X = x1; y = Y1 ;}
Void showarea ()
{Cout <"area of point is:" <0.0 <Endl ;}
};

Class circle: Public point // circle class
{Int radius;
Public:
Circle (int x, int y, int R): Point (x, y) {radius = r ;}
Void showarea () {cout <"area of circle is:" <3.14
* Radius <Endl ;}
};

Void disparea (const point * P) // multi-State program segment
{P-> showarea ();}
Void main ()
{Circle C1 (1, 1); disparea (& C1 );
}
The running result of the program is 0.0 (the correct result is 3.14). The error is caused by the function call in the expression P-> showarea ().

This function is bundled into the function body during compilation so that the function call in this expression executes the showarea () of the Point class (). Therefore

When the sequencer implements a derived class and changes the operation implementation in the base class, the virtual function mechanism provided by C ++ can tell the compiler about this change.

Before placing the keyword virtual in the class point function description of the function (Virtual void showarea (), other parts of the program

If the score remains unchanged (circle: showarea () automatically becomes a virtual function), the compiler will not call the function P-> showarea ().

Generate related code by static bundle (bundle during compilation/connection), so that function calls are related to the bundle of the code to be executed.

Work is performed when the program is running, so that the running result of the above program is 3.14. A dynamic bundle is called a bundle when the program is running.

Yes.
Using Virtual functions, you can use the same function name in the base class and derived class to define different implementations of the function, thus implementing an Interface

, Multiple methods ". When you use a base class pointer or reference to access a virtual function, the software system will point

Or reference the actual object to determine the virtual function version of the class where the called object is located.
The C ++ language also adds a pure virtual function mechanism to better design the inclusion polymorphism. For the class hierarchy of the structure shown in 1 (,

If there is a function "Void display (void);" in each class, how can they be uniformly processed by polymorphism?

? For this type of problem, we should first design an abstract class to make it the ancestor class of all classes, as shown in 1 (B. The purpose of setting Class A is

It indicates that the display () function method in the hierarchy is used in a unified way (the assignment compatibility rules ensure that the sub-classes of A can follow the instructions of a in terms of syntax.

The display () function is used. polymorphism ensures that the corresponding object class is accessed according to the actual object during execution.

Display () function ).

 

To ensure that the display () function set in Class A is an abstract action and that Class A is an abstract class

In Class A, the virtual function language mechanism declares a member function "virtual void display (void) = 0 ;". Note that

Either display () is defined, or the function is declared as pure again.
From the above analysis, we can see that although the design of Class A is expressed in the inheritance syntax, its main purpose is not to set up for code sharing.

It is designed to improve polymorphism. It is the abstraction of another dimension.
2.2 type parameterized Polymorphism
Parameterized polymorphism is also called non-restricted Generic polymorphism, that is, the type is used as a function or class parameter, avoiding the need for a variety of data types.

Writing different functions or classes reduces the burden on designers and increases the flexibility of program design.
A template is a tool for implementing parameterized polymorphism in C ++. It can be divided into function templates and class templates.
The member functions in the class template are all function templates, so the function templates serve the class templates. Class templates are used to represent arrays, tables,

Matrix and other data structures, because the representation of these data structures and the selection of algorithms are not included in

Type. The following is the definition of a general array template.
Template <class T, int n>
Class Array
{T elem [N];
Public:
Array () {for (Int J = 0; j <n; j ++) ELEM [J] = 0 ;}
T & operator [] (INT index) {return ELEM [Index];}
Void Modi (INT index, T value) {ELEM [Index] = value ;}
};
T is a type parameter, and N is a constant parameter. The actual values of T and n are specified when a specific class instance is generated. Class template <>

It can include any type parameter or constant parameter, but should have at least one parameter. In the class template definition, it is usually used in programs.

The type parameter is used wherever the type is specified. Constant parameters can be used wherever a specific type constant expression is used.
The member function template can be defined in a class template or in a class outside the class, for example:
Template <class T, int n>
T & array <t, n >:: operator [] (INT index) {return ELEM [Index];}
When a specific class is generated by a class template, you must specify the type (value) represented by the parameter ). For example, one element type is int,

The array class with a length of 100 is represented by the Type expression array <int, 100>. This type expression is used to describe the array class

Image. For example:
Array <int, 100> A: // generates the object A of a specific class
A. Modi (); // access the member function of object
Once the class template generates an object and specifies the type in the parameter table, the compiler will

These types are fully mandatory.
In C ++, You can reload multiple function templates with the same name, or you can reload one function template and one function with the same name.

For example:
Template <class T> T min (t a, t B) {return a <B? A: B ;}
Template <class T>
T min (t a, t B, T c) {T x = min (a, B); Return min (x, c );}
Int min (int A, int B) [return a <B? A: B ;}
When min (3rd) is called, functions are called. When min (3.8.5.9) is called, the compiler generates a new letter based on the template with two parameters.

Min (double, double); Call min (, 76), the compiler generates a new function min (INT,

Int, INT); When min (56.3,) is called, the compilation will provide an error message indicating that the function cannot be generated from the template above.

Min (Double, double, double), because the compiler does not have type forcing during type derivation.
The template describes one group of functions or one group of classes. It is mainly used to avoid repeated coding tasks by programmers, greatly simplifying and facilitating

Program Design for objects.
2.3 heavy load Polymorphism
Overload is the simplest form of polymorphism, and adds more flexibility and scalability to the programming language. It is divided into operators.

Overload and function overload.
C ++ allows you to redefine the semantics of an existing operator for a class so that the predefined operator can operate class objects. A non-

The persuasive example is the insert operation of the count object (<). Because its class defines the bitwise left shift operator "<",

Function, so that the output of C ++ can be carried out in the same way, it is very easy to learn. In addition, add a complex class for output.

Function (expansion) is also very simple, do not break the original output logic.
C ++ requires that operators be overloaded in the form of functions, which can be a member function of a class or a member function of a class.

A udf is also called an operator function. It is different from a function that uses a member function to overload an operator. The latter is a class.

A member function, which is a member function of the class and is a general function independent of the class. Note that when operators are overloaded, their priority cannot be changed.

Level, cannot change the number of operations required for these operators.
Redefining an existing function is called a function overload. In C ++, both the general function and the member function of the class can be overloaded. For example

The constructor can overload the definition to initialize class objects in several different ways. It also allows the member functions of the derived class

When a member function of the base class is reloaded, the virtual function is reloaded in this form, but it is a dynamic reload method, that is, the so-called "dynamic

Association (bundle )".
2.4 forced Polymorphism
Forced type conversion. The C ++ language defines the conversion rules between basic data types, namely:
Char-> short-> int-> unsigned-> long-> unsigned long-> float-> double-> long

Double
The assignment operation is a special case and the above principles are no longer applicable. When the type of the right operand of the value assignment operator is different from that of the left operand

The value of the right operand is converted to the type of the left operand, and then the converted value is assigned to the left operand.
Programmers can use three forced type conversion expressions in expressions: ① static_cast <t> (E); ② T (E); ③ (t) E

. Either of them can change the rules used by the compiler to enforce the required type as needed. E Indicates

An operational expression. t represents a type expression. The third expression is the style used in the C language. In C ++, it is recommended that

To use this form again, select the first form. For example, set the type of object F to double and its value to 3.14. Expression

Type static_cast <int> (f) is set to 3 and the type is int.
There must be a prerequisite for conversion between class types and other data types through constructors, that is, there must be

Only one constructor with non-default parameters can be converted from the parameter type to the class type through the constructor.

You cannot convert a class type to another type. The class type conversion function is used to convert the class type to other types.

Is a kind of explicit type conversion mechanism. Note the following points for the design of conversion functions: ① The conversion function must be

Class member functions; ② The Conversion Function cannot specify its return value type; ③ the Parameter Line of the Conversion Function cannot have any parameters.
The type check is forced to complicate, especially when heavy loads are allowed, leading to ambiguity that cannot be resolved. Note this when designing a program.

Avoid the Ambiguity Caused by force.

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.