Chapter 18

xiaoxiao2021-03-06  14

Chapter 18

This chapter explains how to use the C overload function and the overload operator.

Including some of the topics below:

* Overview overview

* Description Match

* Parameter matching

* The address of the overload function

* Overload operator

Overview overview

With a C language, you can overload the function and operator. The overload is an application that provides a variety of definitions for a given function name in the same range. The delegate compiler selects the version of the appropriate function or operator based on the parameter called the function. E.g:

Double Max (Double D1, Double D2)

{

RETURN (D1> D2)? D1: D2;

}

Int Max (int I1, INT I2)

{

RETURN (I1> I2)? i1: i2;

}

As an overload function, the function MAX is used in the program as follows:

Main ()

{

INT i = max (12, 8);

Double D = Max (32.9, 17.4);

Return i (int) D;

}

In the first example, the maximum value of two integer variables is required, so the function (int, int, int) is called. However, in the second case, the two parameters are floating-point, so the modified function is Max (Double, Double).

Differences in parameter types

The difference between the overload function is the type of parameter with different initial values. Thus, a given type of parameters and references to this type are identical in the sense of overloading. They are seen as the same because they use the same initial value. For example, Max (Double, Double) and (Double &, Double &) are exactly the same, indicating that two such functions can cause errors.

For the same reason, the modified function parameter type with the modifier const and volatile is not different in the sense of overloading.

However, the mechanism of the overload function can distinguish between references and references for const or volatile modification and basic types. This makes it possible to have the following code:

#include

Class over

{

PUBLIC:

OVER () {cout << "over default constructor / n"}

OVER (over & o) {cout << "over & / n";}

Over (const over & co) {cout << "const over & / n";}

OVER (Volatile over & vo) {cout << "Volatile over & / n";

}

void main ()

{

OVER O1; // Call the default constructor

OVER O2 (O1); // Call over (over &)

Const over o3; // Call the default constructor

OVER O4 (O3); // Call over (Const over &)

Volatile OVER O5; // Call the default constructor

OVER O6 (O5); // Call over (Volatile Over &)

}

Pointer to the Const and Volatile objects and pointers pointing to their basic types are different in terms of heavy load sense.

Restriction of overload function

Whether a set of overload functions is acceptable:

* Nothing in this group of overloadeds must have different parameter tables.

* With the same type of parameter, different overload functions only on the return value type can cause errors.

Microsoft Special Office

Users can overload the NEW operator only based on the return type. Especially in the description-based memory mode modifier is not at the same time.

Microsoft End

* The overload of the member function cannot be static based on one instructions, and the other is not static.

* Typedef Description Non-new types are not defined, and they introduce a synonym for existing types. They cannot affect the overload mechanism. Consider the following code:

Typedef char * pstr;

Void Print (Char * sztoprint);

Void Print (PSTR SZTOPRINT); the two functions have the same parameter table, PSTR is synonymous with type char *. In a member range, such a code will generate an error.

* Enumeration Type is some distinctive type, so you can distinguish the overload function.

* From the sense of the distinction function, the type "array" and "pointer" are the same. It is correct for a one-dimensional array. Therefore, the following overload function has conflicted and an error message is generated:

Void Print (Char * sztoprint);

Void Print (Char Sztoprint []);

For multi-dimensional arrays, second, and subsequent dimension, they can be used to distinguish the overload function:

Void Print (Char Sztoprint []);

Void Print (Char Sztoprint [] [7]);

Void Print (Char Sztoprint [] [9] [42]);

Description match

Any two functions having the same name may refer to the same function, or two different functions of the heavy load may be referred to as the same function. If the parameter list of the instructions contains the same parameter type (as described above), this function explains the same function; otherwise they refer to different functions selected with overload selection. The scope of the class is strictly defined, so a function in which the function described in the base class is the same as the function described in the derived class. If a function described in the derived class is the same name as the function described in the base class, the function of the derived class will hide functions in the base class without causing the function overload. The block range is also strictly defined, so a function in which a function described in the file range is not in the same range. If a function illustrated in a local range has the same name in the same file, the partially described function will hide the functions described in the file range without causing overload. E.g:

#include

Void Func (INT i)

{

COUT << "Called file-scoped func: << i << endl;

}

Void Func (Char * SZ)

{

Cout << "Called Locally Declared Func:" << SZ << Endl;

}

void main ()

{

// Describe local FUNC functions in main

Extern Void Func (Char * SZ);

Func (3); // Error: Function FUNC (int) is hidden

FUNC ("S");

}

The above code gives two definitions of the function func. A function definition as a parameter as a parameter is partially local because there is an extern statement. Therefore, the definition of the function of INT is hidden, so the first call to the FUNC function is wrong.

For a member function of the overload, the different versions of the function can be given different access. They are still considered in the range of classes, so they are overloaded functions. Consider the following code, the member function deposit is overloaded; a version is public, and another version is Private.

Class Account

{

PUBLIC:

Accent ();

Double Deposit (Double Damount, Char * Szpassword);

Private:

Double Deposit (double damount);

INTVALIDATE (CHAR * SZPASSWORD);

}

The above code is to provide an Account class, where the deposit function is executed, requiring a correct password. This is achieved with overload. The following code gives how to use this class, as well as error calls for private member functions deposits:

void main ()

{

// Assign a new object of an Account type

Account * pACCT = New Account

/ / $ 57.22 Error: Call a private function

PACCT-> Deposit (57.22);

/ / 47.22 and provide a password, correctly call a public function PACCT-> Deposit (57.22, "pswd");

}

Double Account :: Deposit (Double Damount, Char * S2Password)

{

Validate (szpassword))

Return Deposit (DAMOUNT);

Else

Return 0.0;

}

Note that in Account :: Deposit, the private member function deposit is called, this call is correct. Because Account :: Deposit is a member function, it has the right to access the private member of the class.

Parameter matching

This function is called for a suitable function. "Suitable" here is one of the following:

* Discover a full match.

* A Trival Conversion.

* Execute an integer parameter upgrade.

* There are standard conversions for the required parameter type.

* There is a user-defined conversion of the required parameter type (whether the conversion operator is still a constructor).

* Discover the parameters represented by (...).

The compiler creates a candidate function set for each parameter. The candidate function is a function that can be converted to the form of parameter type in this location. Each parameter has established an optimal matching function set. The selected function is the intersection of all of these collections. If the intersection contains multiple functions, the overload is an unity and generate an error. The final selected function is always more matching in this group, at least one parameter is more matching. If the situation is not like this (if there is no more matchr), the function call generates an error.

Consider the following code (the function indicates form 1, form 2 and form 3 for the discussion below):

Fraction & Add (FRACTION & F, Long L); // Form 1

Fraction & Add (long L, Fraction & f); // Form 2

FRACTION & Add (Fraction & F, Fraction & f); // Form 3

FRACTION F1, F2;

Consider the following statement:

F1 = add (f2, 23);

The front statement constructs two collection:

Collection 1: Candidates for the first parameter type FRACTION

Collection 2: You can convert the second parameter type to an integer function form 1 form 1 (int available standard conversion to long type) Form 3

In the function of the collection 2, there is a hidden conversion from the type of the type of reference type to the type of reference. There is a function in these conversions to the cost of such a conversion.

The intersection of these two sets is form 1. For examples of ambiguous function call, as follows:

F1 = add (3, 6);

The above function call generates the following collection:

Collection 1: The first parameter can have a candidate function for integer parameters

Collection 2: The second parameter can have a candidate function for integer parameters

Form 2 (INT can be converted to long type with standard conversion)

Form 1 (INT type can be converted to long type with standard conversion)

Note that the intersection of these two collections is empty set, so the compiler generates an error message. For parameters match, a function with N default parameters is used as N 1 different functions, each function has a different number of parameters.

(...) is a wildcard; it can match any arguments. If you are not extremely carefully designed for your overload function, there will be many sets of unity.

Note: The error of the overload function is discovered until it comes to the function call. At that time, a collection was established for each parameter called in the function, and you can find that there is a non-defense overload existence. This means that erliness will remain in your code until they are discovered by a particular function call.

Parameter matching and this pointer

The class member function will be treated in different ways according to whether it is described as Static. Because the non-static member function has an implied parameter to support the THIS pointer. Non-static functions are considered to be more than a parameter than static functions.

In addition, their description is equivalent. These non-static member functions require an implicit THIS pointer to match the type of object that calls this function. Or for the overload operator, they require the first parameter to match the object of the operator (see the "overloader operator" behind the overloader of the manipulator).

Unlike other parameters of the overload function, when matching the THIS pointer parameters, the temporary object will not be introduced, and the conversion will not be tried). When the member selector (->) is used to access member functions, the THIS pointer is class-name * const type. If the member is explained as const or volatile, the type is corresponding to const class-name * const or volatile class-name * const.

In addition to adding an implicit & (taking address operator) to the front of the object name, the member selectors (.) Work in the same way. The following example shows how this works:

// Expression encountered in the code

Obj.name

// How to treat it with the compiler

(& obj) -> Name

The left operation number of the arithmetic matching operator -> * and. * (Pointing to the member's pointer). And -> is also treated.

Parameter matching and conversion

When the compiler is trying to match the parameters in the function description, if a precise match is not found, the compiler can support standard or user-defined conversions to obtain the correct type. The application of the conversion is limited by the following rules:

* The transition sequence containing multiple user custom conversions is unacceptable.

* The transition sequence that can be shortened by removing intermediate conversion is also unacceptable.

The result of the conversion (if any) is called an optimal matching sequence. Use standard conversion (Chapter 3 "Standard Conversion"), there are several ways to convert an INT type object to UNSIGNED LONG type:

* Convert the INT type to Long type, then convert it to unsigned long

* Convert the INT type to the unsigned long.

The first method, although the desired goals are reached, but not a sequence of best match, because there is a shorter matching sequence.

Table 12.1 gives a set of conversions called usual conversion. They play a limited role in which a sequence is the best match. The steps of usual conversion affect the sequence of sequences are discussed below.

Table 12.1 Usually Conversion

From Type Conversion to Type Name Type Name & Type Name & Type Name Name [] Type Name * Type Name (Selection Table) (Selection Table) Type Name CONST Type Name Name Volatile Type Name Name * Const Type Name * Type Name * Volatile Type Name *

The order of conversion is tested as follows:

Exactly match. Accurate match between the parameter type of the call function is always the best match between the types described in the function prototype. The usual conversion sequence is generated to precisely match. However, it is generally believed that the sequence of these conversions is better than the sequence of the following conversion:

* From the pointer to the pointer pointing to Const (Type * to const type *).

* From the pointer to the pointer to the Volatile (Type * to Volatle Type *).

* From reference to reference to Const (Type & to Const Type &).

* From reference to reference to Volatile (Type & to Volatile Type &).

2. Use the matching of parameters. Any sequence that is not classified as a precise match is included only with the necessary parameters (from FLOAT to DOUBLE), the sequence of usual conversion will be classified as a match using parameters. Although this match does not have precise match, the matching matching of parameters is better than the matching of standard conversion.

3. Use the matching of standard conversion. Any sequence that cannot be mated to exact match or parameter enhancement only contains only standard conversion, the usual conversion is classified as a matching using standard conversion. In this match, you must follow the rules below:

* Convert a derived pointer to a pointer pointing to its direct base class or a non-direct base class than converted to VOID * or const void * more appropriate.

* Convert a pointer of a derived class into a pointer to the base class, resulting in a pointer to the closer base class to the direct base class. Suppose the class level shown in Figure 12.1.

Switching from Type D * to Type C * Better from Type D * to Type B * Better. Similarly, the conversion from type D * to type B * is better from type D * to type A *.

The same rules are also applicable to reference conversions. From Type D & to Type C & Better from Type D & to Type B & Better, so on.

This rule also applies to the conversion to the member pointer. From Type T D: * to Type T D: * to Type T D: * to Type T D: * The conversion of Type T D: * is better, and this is pushed (where T is the type of member). The above rules apply to the same given derivative path. Consider the level map in Figure 12.2. The conversion from type C * to type B * is better than the conversion from type C * to type A *. The reason is that they are on the same path. However, the conversion from type C * to type D * is not better than from type C * to type A *, because the conversion is along different paths.

4. Use the matching of custom conversion. Such sequences cannot be classified as precise matching, using parametric lifting or matching of standard conversion. Matching sequences that are classified using custom conversion must contain only user-defined conversions, standard conversion, or usual conversions. The matching of custom conversion is better than the matching of the illegal match, but it is better than the matching of standard conversion.

5. Use the provincial omnifier (? Match. Any sequence of monitors in any matching function is classified as a matching of the illegal match. This match is the worst match.

User-defined transformations apply to the case where the parameters of the internal parameters or the existence of conversion. This conversion selection is based on the type of parameters to be matched. Consider the following code:

Class UDC

{

PUBLIC:

Operator int ();

Operator long ();

}

Void Print (INT I);

DC UDC; Print (UDC); user-defined conversion for class UDC is an INT type and long type, so compiler can accept conversion from the type of object to be matched.

There is a conversion from UDC to INT, so this conversion is selected. The standard conversion can be used for the return value of parameter and user-defined transformation during the parameter matching process. Therefore, the following code is workable:

Void Logtofile (long L);

UDC UDC;

Longtofile (UDC);

In the above example, the user-defined conversion Operator long converts the UDC type to the long type. If it is not defined from the UDC type to the conversion, this conversion will be performed as follows: first use custom conversion to convert the UDC type to an INT type, and will use the standard conversion from the INT to the long type to match the description Pass.

If the matching parameters need to customize the conversion, the standard conversion is not considered when evaluating the best match. Even if there are multiple candidate functions that require user custom conversion, the standard conversion is not considered. In this case, these functions are equivalent. E.g:

Class UDC1;

{

PUBLIC:

UDC1 (int); // User-defined conversion from INT type

}

Class UDC2

{

PUBLIC:

UDC2 (long); // User-defined conversion from Long type

}

Void Func (UDC1);

Void Fuce (udc2);

UNC (1);

Both of these two versions require user-defined conversions: convert the INT type to class type parameters. Possible conversion is as follows:

* Transition from INT to UDC1 (user-customized conversion).

* From the INT type to the LONG type conversion, then convert to a UDC2 type (two-step conversion).

Although the second conversion method requires standard conversion and user-defined conversion, these two conversions are equivalent.

Note: The user-defined conversion is considered to be converted through the constructor or by initializing conversion (conversion function). These two methods are considered to be equal when considering optimal match.

Overload function

Without a parameter table, the name of using a function will return the address of the function, for example:

INT FUNC (INT I, INT J);

INT FUNC (long L);

INT (* PFUNC) (int, int) = func;

The first FUNC function will be selected in the previous example, and its address is copied into the PFUNC. Search functions by the full match of the parameters, the compiler can determine which version of the function is selected. The parameter table described in the overload function matches one of the following.

* An initialized object (such as the previous example)

* The left side of the assignment statement

* Part of a function

* Guanyuan for a custom operator

* Return value of the function

If a complete match is not found, the expression of the function address is unity and generates an error.

Note that although a non-member function FUNC is used in the above example, the same rule applies to the address of the member function to take load.

Overload operator

With C , you can redefine the functions of most internal operators, which can be redefined or overloaded under global mode or in mode. The overload operator is implemented with a function, which can be a member function or a full-class function. The name of an overloaded operator is OperatorX, where x is an operator that appears in Table 12.2. For example: To overload an addition operator, you can define a function called Operator . Similarly, the overload / assignment operator ( =) can define a function called: Operator =. Although these operator functions are typically hidden by the compiler when the compiler is included, they can be explicitly called in any member function or non-member function.

Point pt;

Pt. Operator (3); // Call the addition operator to PT. plus 3

Table 12.2 Reconfifiable Operators

Operator name type, comma double eye! Logic is not single! = Inequalized buddy% Table 2 Bocal% = Timing / assignment Better & Bit and Bit and Note Address Single && Logic and Biography & = Bit and / assignment bind () function call - * Multiplication Double object * Pointer Indirect reference single-grade * = Multiplication / assignment double point addition double point single plus single increase 1 single = addition / Assignment binding - subtraction binding - Take the anti-single-purpose - minus 1 single-目目 - = subtraction / assignment double -> Member Selection Better -> * Pointer to the member's pointer selection double / division double / = division / assignment Both greater than binding> = greater than / assignment double eyes >> right Movered bide >> = right shift / assignment double [] array subscript - ^ ^ ^ ^ ^ ^ Di or / assignment double | Bit or double | = Bit or / assignment double eye || logic Or both eyes ~ ask for a single-grade DELETELETE - NewNew -

* There are two ways to increase 1 and minus 1 existence: prefix methods and suffix methods.

The constraints of each classification of the overload operator, "single operator", "binocular operator", "assignment", "function call", "subscriber access", "class member access", "" And minus 1 ".

Table 12.3 Operators that cannot be overloaded

Operator name. Member selection. * Point to the selection of member pointers :: Range Dismissue?: Conditional operator # Prerequisites ## Prerequisite symbol

General rules for operators overload

The following rules constrain how the overload operators are implemented, but they do not apply to the New and Delete operators. These two operators are discussed separately in Chapter 4.

* Operators must be either a member function, or a parameter with a class, or a parameter of an enumerated type, or a reference to a class, or a reference for a certain enumeration. E.g:

Class Point

{

PUBLIC:

Point Operator <(Point &); / / Description A member operator overload

...

// Describe the addition operator

Friend Point Operator (Point &, Int);

Friend Point Operator (INT, POINT &);

}

The above example code illustrates less than the operator member function; however, the addition operator is explained as a global function and has a friend access attribute. Note that multiple implementations can be provided for a given operator. In the example of the addition operator above, two implementations are provided in order to facilitate the exchange of addition. Just like these operators, add Point to Point, and add int to Point operators to be implemented.

* Operators should follow their number of specified priorities, packets and operands. Therefore, it cannot be expressed to add 2 and 3 to a Point object.

Meaning, in addition to adding 2 to X coordinates, add 3 to Y coordinates.

* Single Operator Description As a member function without a parameter; if you explain the global function, take a parameter.

* Dibae operator Description As a member function, only one parameter; if you explain the global function, bring two parameters.

* All overload operators can be derived inherited in addition to assignment (Operator =).

* The first parameter of the member function of the overload operator always activates the class type parameter of the operator's object (the operator defined class, or defines the derived class of the class of the operator). Conversion is also supported for the first parameter. Note that the meaning of any operator may be completely changed, which includes the address (&), assignment (=), the meaning of the function call operator. , The same, the internal type can be changed due to the use of operator overload. For example: The following four statements are completely equivalent to the completion of the evaluation:

VAR = var 1;

VAR = 1;

VAR ;

VAR;

For class types that overload operators, this conviction is unconventional, and for the use of these operators in the basic type, it is relaxed for overloaded operators. For example: add / assignment manifest, when applied to basic types, requires its left operating number to be l values; but there is no such requirement after this operator is overloaded.

Note: It is best to follow the internal type mode for operator overloading in accordance with consistent considerations. If an overloaded operator is different from its meaning in other context, it will only cause confusion rather than more useful.

The single operator (Table 12.4 gives an individual operator.)

Table 12.4 Overloaded single-grade operator

Operator name! Logic is not addresses the address ~ ask * Pointer indirect reference single-grade plus increase 1-single-point retrore-reduction 1

In the operator given in Table 12.4, the increase in the suffix 1 and the minus 1 operator are discussed in "increasing 1 and minus 1" section.

Note An unique operator is a non-statistial member, and must be described as follows:

RET-TYPE OPERATOROP ()

Where RET-TYPE is a return type, and OP is an operator in Table 12.4.

Description A single operator is a global function, and must be described below:

RET-TYPE OPERATOROP (ARG)

Where RET-TYPE and OP mean the description in the member operator function, Arg is a class type parameter that is operated.

Note: There is no restriction on the return value of the single operator. For example, for a logical non-operator, it is suitable for returning a necessary value. But this is not necessary.

Increase 1 and minus 1

Increase 1 and minus 1 operator put into special classification because each operator has two forms:

* Prefix type 1 and suffix type increase 1.

* Prefix type 1 and suffix type 1.

It is useful when you write overload operators, which provides a version of the prefix and suffix types of this operator. To distinguish these two versions, you must follow some of the following rules: For the prefix-based operator, you can explain the same manner as any other monographic manipulator, and the suffix type should accept an additional INT type.

Important: When an overload function is added 1 and minus 1 operator, additional parameters must be int type, indicating that any other type will generate an error.

The following example shows how to define prefix and suffixes for class Point 1 and minus 1 operator:

Class Point

{

PUBLIC:

/ / Describe the prefix and suffix type 1 operator

Point & Operator (); // Prefix Type 1 Operator

Point Operator (int); // Results increase 1 operator

// Describe the prefix and the suffix type minus 1 operator

Point & Operator - (); // Prefix type minus 1 operator

Point Operator - (int); // Repatriator minus 1 operator

/ / Describe the default constructor

Point () {_x = _y = 0;}

/ / Description Access function

INT x () {return _x;}

Int y () {return _y;}

Private:

INT _X, _Y;

}

/ / Define a prefix-type increase 1 operator

Point & Point :: Operator ()

{

_X ;

_Y ;

RETURN * THIS;

}

/ / Define the hyperfix type 1 operator

Point Point :: Operator (INT)

{

Point Temp = * this;

* THIS;

Return Temp;

}

/ / Define prefix-type minus 1 operator

Point & Point :: Operator - () {

_X-;

_y--

RETURN * THIS;

}

/ / Define the sub-reduction 1 operator

Point Point :: Operator - (int)

{

Point Temp = * this;

- * this;

Return Temp;

}

Use the following function headers to define the same operator in the file range (globally):

Friend Point & Operator (Point &) / / Prefix 1

Friend Point & Operator (Point &, Int) // Respected 1

Friend Point & Operator - (Point &) / / Prefix 1

Friend Point & Operator - (Point &, Int) // Refixed 1

Indicates that the INT type of the reducing 1 minus 1 operator is not ordinary to be used as a parameter transmission. It usually contains 0 values, however it can be used as follows:

Class Int

{

PUBLIC:

INT & OPERATOR (INT N);

Private:

INT_I;

}

INT & INT :: Operator (INT N);

{

IF (n! = 0) // pass a parameter processing

_i = N;

Else

; // no delivery of parameters

RETURN * THIS;

}

...

INT I;

I.Operator (25); // plus 25

As shown above, there is no other syntax except for explicit calls, there is no other syntax that can be used to use an increase 1 minus 1 operator to transfer a function value. A way to achieve this function is to overload = operator.

Bottom operator table (12.5 gives an operator that can be overloaded.)

Table 12.5 Delicious double-purpose operator

Operator name, comma! = = Inequality% = Timing / Assignment & Bit and & & = Bit and / Assignment * Multiplication * = Multiplication / Assignment Add = Adding / Assignment - subtraction - = Substration / Assignment -> Member Selection -> * Pointer to the member's pointer selection / division / = division / assignment greater than> = Equal to >> Right shift >> = right shift / assignment ^ vary or ^ = vary or / assignment | Bit or | = Bit or / assignment || Logic or

Note A binocular operator function is a non-static member function, and must be described in the following form:

RET-TYPE OPERATOROP (ARG)

Where RET-TYPE is a return type, OP is an operator listed in Table 12.5, and Arg is an arbitrary type of parameters.

Note A binocular operator is a global function, and must be described in the following form:

RET-TYPE OPERATOROP (Arg1, Arg2)

The description in RET-TYPE and OP is consistent, and Arg1 and Arg2 are parameters. At least one of them must be class type.

Note: There is no restriction on the return type of the binocular operator; however, most user-defined binocular operators return to class types or class types.

Assignment

The assignment operator is strictly a binocular operator. Its instructions are equivalent to other binocular operators, except for the following conditions.

* It must be a non-static member function. No Operator = can be explained as non-member functions.

* It cannot be inherited by the derived class.

* If there is no default Operator = function, the compiler generates a default function for this class (see the assignment and initialization of membership methods in Chapter 11 "Special Member Functions" for the default Operator = function. ").

Here's how to explain the assignment operator:

Class Point

{

PUBLIC:

Point & Operator = (Point &); // On the right is a parameter

...

}

// Define Assault Operator Point & Point :: Operator = (Point & Ptrhs)

{

_X = ptrhs._x;

_y = ptrhs._y;

Return * this; // Assignment operator returns left

}

Note that the supplied parameters are the right side of the expression. The object returned by the operator maintains the behavior of the assignment operator (after the assignment is complete, the assignment operator will return the value of the left), so that the following statement can be written:

PT1 = PT2 = PT3;

The function call function call operator involves the use of parentheses, which is a binocular operator. The syntax of the function is as follows:

grammar

PRIMARY-ExpRession (Expression-List Opt)

Here, primary-expression is the first operand, which expression-list (may be an empty parameter) is the second operand. Function call operator for multi-parametric operations. This can be done because Expression-List is a parameter table instead of a single parameter. Function call operators must be a non-static member function.

After the function call operator is overloaded, it does not change the behavior called by the function, and how it will only affect the operator when the manipulation is applied to a given class type. For example: The following code is usually meaningless:

Point pt;

Pt (3, 2);

Give the appropriate overload function call operator, this syntax can be used to add 3 units to the X coordinate, add 2 units to the Y coordinates. The following code illustrates the above definition:

Class Point

{

PUBLIC:

Point ()

{_x = _y = 0;}

Point & Operator () (int DX, int DY)

{_X = DX; _Y = DY; RETURN * this;}

Private:

INT _X, _Y;

}

...

Point pt; pt

(3, 2);

Note that the function call operator applies to the object name instead of the function name.

Subscript operation

Just like a function call operator, the subscript operator ([]) is also a binocular operator. The subscript operator must be a non-static member function and has a parameter. This parameter can be any type and indicate the desired array subscript.

The following example shows how to create an INT vector of implementing a boundary check:

#include

Class IntVector

{

PUBLIC:

INTVECTOR (Int Celements);

~ IntVector () {delete_ielements;

INT & Operator [] (int nsubscript);

PRIVATE;

INT * _IELEMENTS;

INT_IUPPRTBOUND;

}

/ / Construct an intVector object

INTVector :: intVector (int Celements)

{

_ielements = new int [CELEMENTS];

_iupperbound = CELEMENTS;

}

// Invetor's subscript operator

INT & INTVector :: Operator [] (int nsubscript)

{

Static int er = -1;

IF (nsubscript> = 0 && nsubscript <_iUpperbound)

Return_ielements [nsubscript];

Else

{

CLOG << "Array Bound Viology." << Endl;

Return Ierr;

}

}

// Test the intVector class

int main ()

{

INTVECTOR V (10);

For (int i = 0; i <= 10; i)

v [i] = i;

v [3] = v [9];

For (i = 0; i <= 10; i) cout << "ELEMENT: [" << i << "] =" << v [i] << ENDL;

Return V [0];

}

In the above example, when I to 10, Operator [] detected a subscript that exceeded the boundary and issued an error message.

Note that the function operator [] is a reference type. This makes it a L value so that the subscript expression can be used on both sides of the assignment number.

Access to class members

Access to class members can be controlled by overloaded member selectors (->). In use, this operator is regarded as a single operator, and the overloaded operator function must be a member function, so the description of this function is:

Class-Type * Operator -> ()

Here Class-Type is the name of the class belonging to the operator. The member selector function must be used as a non-static member function.

This operator (usually using a pointer indirect reference operator) is used to implement the "Sensitive" pointer, which makes the pointer to take effect before indirect reference or count.

Member selectors (.) Cannot be overloaded.

转载请注明原文地址:https://www.9cbs.com/read-46715.html

New Post(0)