You get a bonus - 1 coin for daily activity. Now you have 1 coin

Chapter 3. Overloading Operations

Lecture



Introduction

C ++ defines sets of operations on variables of standard types, such as +, *, /, etc. Each operation can be applied to operands of a particular type.

Unfortunately, only a limited number of types are directly supported by any programming language. For example, C and C ++ do not allow performing operations with complex numbers, matrices, strings, sets. However, all these operations can be performed through classes in the C ++ language.

Consider an example.

Let sets A and B be given:

A = {a1, a2, a3};

B = {a3, a4, a5},

and we want to perform the union (+) and intersection (*) operations of sets.

A + B = {a1, a2, a3, a4, a5}

A * B = {a3}.

You can define a Set- “set” class and define operations on objects of this class by expressing them using operation signs that already exist in C ++, for example, + and *. As a result of the operation, + and * can be used as before, as well as provide them with additional functions (joins and intersections). How to determine which function should perform the operator: old or new? Very simple - by the type of operands. And what about the priority of operations? The previously defined priority of operations is preserved. In order to extend the operation of an operation to new data types, it is necessary to define a special function, called an “operation-function” (operator-function). Its format is:

operator_type_of_pluence operator_array_array (parameters_value) {function_body_of_arrows}

If necessary, a prototype can be added:

operator_type_of_operations operator_array_ (parameters_value)

If we assume that the operator statement operator_name is the name of a certain function, then the prototype and the definition of the operation-function are similar to the prototype and the definition of the usual C ++ language function. The operation defined in this way is called overload.

In order to provide an explicit connection with the class, the operation-function must be either a component of the class, or it must be defined as friendly in the class and it must have at least one parameter of the class type (or a class reference). Calling an operation function is the same as any other C ++ function: operator A. However, the abbreviated form of its call is allowed: a Е b, where Е is the sign of the operation.

created: 2015-12-20
updated: 2021-03-13
140



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

C ++ (C plus plus)

Terms: C ++ (C plus plus)