C is based on C language, supports data abstraction and object-oriented programming languages. C draws the C language expansion section
Many of the best features in many famous languages, such as absorbing operator overload mechanisms from Algo168. Since the C language has a C language one
High execution efficiency and is easily accepted by software personnel who are familiar with C language, and thus quickly spread. But this hybrid object-oriented
Programming language is a new programming language, people have not fully sufficient for many of its potential performance (package, inheritance, polymorphism, etc.)
Geographical solutions and applications have not fully utilized its advantages. Polymorphism is one of the important concepts of object-oriented systems, which refers to the same news
It can be sent to the object of the parent class and the object of its subclass. This article focuses on discussing the application of polymorphism in programming.
1 polymorphism implementation
In general, polymorphism refers to the ability of a program to handle multiple types of objects. In C language, this polymorphism can
By compulsory polymorphism, heavy-duty polymorphism, type parametric polymorphism, including 4 forms of polymorphism. Type parameterization polymorphism and containing polymorphism
It is called a general polymorphism that is used to systematically engraving a set of types of semantics. Heavy duty polymorphism and mandatory polymorphisms are called special polymorphisms,
It is used to portray the relationship between the type of semantics. Contains polymorphism means that the object of the type T can be handled by sub-type, and the pair of sub-type S of the type T can also be handled.
Icon, the program section is called a polymorphic block. Public inheritance can implement subtypes. In the containment, one object can be seen as a
The same class, the existence of the relationship means the presence of a common structure. Contains polymorphics exists in many languages, such as integer types
Subcommage constitutes 1 subtype. Objects in each subtype can be used in a high level type, all of the high-level types can be
For the next level of the next level. There is a kind of polymorphism in the C in the public, each class can directly inherit the parent class or multiple parents.
Class, such as statement class dpublic P1, public p2 {...}; indicate classes D is the subtype of class P1 and class P2, respectively. Type parameterization polymorphism means that when 1 function (class) is unified, these types show some public language when operating a number of types of parameters.
The characteristic, and the function (class) is used to describe this feature. In type parameterized polymorphism, 1 polymorphism function (class) must have at least
1 type parameters, this type parameter determines the type of operand in each execution. This function (class) is also known as the class function (class)
. The type of parameterized polymorphism is widely used, called the purest polymorphism. The overload refers to a different function or operator named with the same name. Function overload is C to operate in general programming languages
The expansion of the carrier mechanism allows the same name with the same or similar meanings, as long as the number of parameters, the order or type of
Like it. For example: int min (int x, int y); // finds the minimum INT Min (int X, int y, int z) of 2 integers; // Search for the minimum number INT min (int N, int A []); // Request the minimum of n integers When the user requests to increase the function of comparing 2 string size, simply increase:
CHAR * min (char *, char *);
And how to use this group of functions does not need to change, Min's functional expansion is easy, that is, the maintenance is relatively easy, and also mention
Highly understandable, "min" means a function of the minimum value. Mandatory refers to semantic operations that convert a type of value to another type of value to prevent type errors. Type conversion
It can be implicit, completed during compile, such as statement D = i converts an integer variable to a real shape; it can also be explicit, which can be done during dynamic operation. Overall, general polymorphism is true polymorphism; special polymorphism is only the polymorphism of the surface. Because overload is only allowed
A symbol has a variety of types, and the values it represents have different, incompatible types, respectively. Similarly, implicit type conversion is also
Not a real polymorphism, because each value must be converted to the required type before the operation begins, and the output type is also independent of the input type.
In contrast, subclasses and inheritance are real polymorphism. Type parameterized polymorphism is also a pure polymorphism, the same object or function is not
The same type of type is uniformly used in the following, without the need for implicit type conversion, runtime detection, or other limits.
2 polymorphism
2.1 Include Polymorphical C implements a virtual function to implement the polymorphism, the virtual function provides a more flexible polymorphism mechanism for C , this polymorphism is
When the order is running, it can be determined, so the virtual function is the essence of polymorphism, and at least a class containing a virtual function is called a polymorphism class. Contain more
Samples are very frequent in programming. Derive class inheritance base class, or, the operation of the base class can be used to operate the object of the derived class, when the base class does not
When adapting to the derived class, the derived class needs to be kept in the base class, see Void Circle :: Showarea () in the following example. #Include
Class Circle: Public Point // Round 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 * RADIUS << Endl;}};
Void Disparea (Const Point * P) // Polymorphic block {P-> showarea ();} void main () {Circle C1 (1, 1, 1); Disparea (& C1);} The operation result of the program is 0.0 (The correct result should be 3.14), the reason for the error is: the function adjustment in the expression P-> Showarea ()
The function calls the function in this expression call to execute the SHOWAREA () of this expression in this expression. To this end,
When the sequence member changes the operation implementation in the base class, the sequence of operations can tell the compiler in the C , which is the function of the function of the function in the keyword virtual (Virtual). Void Showarea ()), Other Universities
The division remains unchanged (Circle :: ShoWarea () automatically be virtual function), the compiler will not call the function to call P-> showarea ()
Row static beam (beam in compilation / connection) generates related code, making the function call to the beam of the code it should execute
Working is performed at runtime, so that the operation results of the above programs are 3.14. Branding is called dynamic bundle at runtime
set. Using virtual functions, you can use the same function name definition function in the base class and derived class to implement "an interface
, Various ways. "When you use a base class pointer or a reference to the virtual function, the software system will point to the runtime pointer or reference.
Or reference the actual object to determine the virtual function version of the call to the object. The C language also adds pure virtual function mechanisms to better design the polymorphism. For class levels of the structure shown in Fig. 1 (a),
If there is a function in each class, "Void Display (Void);" So, how do you have a unified process of polymorphism?
? This kind of problem should be designed to design an abstract class to make it a ancestral class of all classes, as shown in Figure 1 (b). The purpose of setting class A is
It illustrates the method of unified Display () function (assignment compatibility rules) to the child grandson can press A
The way the display () function is used; the polymorphism is guaranteed from the semantic, and the corresponding object class is accessed according to the actual object.
Display () function).
In order to ensure that the display () function set in class A is an abstract action, and can explain that class A is an abstract class, in C , it can be pure
The virtual function language mechanism declares a member function "Virtual Void Display (Void) = 0 in class A. Please note that in class a
DISPLAY () definition is given in the children's grandson, or the function is declared as pure. As can be seen from the above analysis, the design of class A is expressed by inheritance syntax, but its main purpose is not to be shared for code.
Instead, it is designed to improve polymorphism, it is an abstraction of another dimension. 2.2 Type Parametric Polymorphization Polymorphism, also known as the unrestricted class polymorphism, which is about to type as a function or class, avoiding various different data types.
Write different functions or classes, reduce the burden of designers, and improve the flexibility of programming. Templates are Tools for C to achieve parameterized polymorphism, divided into function templates and class templates. The member functions in the class template are function templates, so the function template is served for class template. Class template in representing arrays, tables,
When the matrix is classified, it is particularly important because the representation of these data structures and algorithms are not subject to the elements they contain.
The impact of type. Below is a definition of a general array class template. Template
The type specified by the type uses the type parameters to use constant parameters anywhere in the usual type of constant expression. Members Functions Templates can be defined in class templates, or be placed outside of the class, for example: Template
An array class with a length of 100 is represented by type expressions array
Icon. For example: Array
It is fully enforced to these types. In C , you can override a function template defined by multiple identities, or 1 function template can be redefined with 1 same name function.
For example: Template INT, INT); calls MIN (56.3, 48, 71), compiling will give an error message, indicating that functions cannot be generated from the template above. MIN (Double, Double, Double), because the compiler is derived when the type is derived, there is no type forced. The template describes 1 set of functions or 1 groups, which is mainly used to avoid programmers to repeat the encoding work, greatly simplified, convenient Design to the object of the object. 2.3 Overloaded polymorphism is the maximum form of polymorphism, and more flexibility and scalability are added to the programming language, it is divided into operators. Overload and function overload. C allows for a semantics of the already operator to make the system to operate the system. One of the C language An example of a convincing force is an insertion operation of a count object (<<). Due to the definition of the right left shift operator "<<" The functions of the load make the output of C can be carried out in the same way, and it is very easy to learn. And, add one to the output of multiple classes The function (expansion) is also very simple and does not have to destroy the original output logic. C specifies that the operator is overloaded as a function, which can be overloaded as a member function, or you can overload a friend function of the class. The function of the user's heavy-duty operator is also known as an operator function, which is different from the function of the member function overload operator, the latter itself is in the class. Member functions, and it is a class friend function, which is a general function independent of class. Pay attention to the overload operator, you cannot change their priority. Level, you cannot change the number of operands required for these operators. Refine existing functions is called function overload. The overloaded general function is allowed to be overloaded in C , and a member function of the overloaded class is also allowed. If The constructor performs overload definition, allowing the program several different ways to initialize class objects. Allow members of the derived class The member function of the reloading base class, the virtual function belongs to this form of overload, but it is a dynamic overload mode, that is, the so-called "dynamic" Edge (beam) ". 2.4 Forced polymorphism, also known as type conversion. C language defines the conversion rules between basic data types, namely: char-> short-> int-> unsigned-> long-> unsigned long -> float-> double-> longdouble assignment operation is a special case, the above principle is no longer applicable. Different from the type of right operator of the assignment operator and the type of left operating When the value of the right operand is converted to the type of the left operating number, then the converted value is assigned to the left operation. Programmers can use three forced type conversion expressions in their expressions: 1static_cast . Any one of them can change the rules used by the compiler to force the required type according to their own wishes. Where E represents An operational expression, T represents a type of expression. The third expression form is the style used in the C language, in C , it is recommended not To use this form, you should choose to use the first form. For example, the type of object f is Double, and its value is 3.14. Be expressed The value of Static_cast Only one non-default parameter constructor, through the constructor, the conversion of class types can only be converted from the parameter type to class type, and think It is not possible to turn a class type to other types of conversions. Class type conversion functions are dedicated to convert class types to other types of this type It is a mechanism similar to explicit type conversion. Special attention to the design of the conversion function should be taken: 1 The conversion function must be The members of the class; 2 conversion functions cannot specify its return value type; 3 Conversion functions cannot have any parameters. Force the type inspection complicates, especially in the case of allowing overload, it can cause unusually dismissive, in the program design Avoiding the amazing zone of mandatory.