Operator overloading operator

Source: Internet
Author: User

Found a good article:

Reproduced:

This paper mainly summarizes the operator overloading and C + + operator overloading summary from C + +.

What is operator overloading

Operator overloading is to give multiple meanings to existing operators, causing different behavior to occur for different types of data of the same operator scope. Such as:

View Code

In this program "+" to complete the addition of two number of numbers, but also completed the double-precision addition operation. Why can the same operator "+" be used to perform addition operations on different types of data? This is because C + + has already made the appropriate overloads for the "+" operator for the predefined base data types. When the compiler compiles an addition expression for different types of data, the addition operator overload function of the corresponding type is automatically called. However, the predefined basic data types provided in C + + are limited after all, and often require a user-defined data type when solving some practical problems. Like the plural in high school math:

View Code

If we create two complex numbers, we use the "+" operator to add them directly:

1 Complex COM1 (TEN), COM2 (), sum;2 sum = com1 + COM2;

You will then be prompted for errors that do not have a "+" operator that matches these operands. This is because the complex class type is not a predefined type, and the system does not have to overload the addition operator function for that type of data. C + + provides a method for operator overloading, that is, operator overloading functions. The function name is specified as operator immediately after the overloaded operator. For example: operator+ (), operator* () and so on. Now let's declare an overloaded function of an addition operator for the above program to complete the addition of complex numbers:

View Code

Results:

  

In the example code above, invoking an operator overload function can also be called as operator+ (COM1,COM2), in fact Com1+com2 is translated into the same form as the program interpretation. But the direct use of com1+com2 form more in line with the people's writing habits.

Operator overloading of classes

The operator overloading function in the above example is a class that does not belong to any, and is a global function. Because data members in the complex class (plural Class) are public in nature, operator overloading functions can be accessed. But what if it's defined as private? In fact, in the actual operator overload function declaration, it is generally defined as a friend function of the member function or class to manipulate the class.

Operator overloading functions as a friend function of a class
Class Name {    friend return type operator operator (formal parameter list);} Out-of-class definition format: return type operator operator (parameter table) {    function Body}

The friend function overloads the binocular operator (there are two operands, usually the left and right of the operator), and the number in the parameter table is two. If you overload a single-mesh operator (with only one operand), then there is only one parameter in the parameter table.

1. Friend function Overloaded binocular operator (+)

View Code

Results:

  

2. Friend function overloading single-mesh operator (+ +)

View Code

Results:

  

An operator overload function can return any type, even void, but usually the return type is the same as the class type it operates on, which allows the operator to be used in complex expressions. For example, the above binocular operator overload function code in the main () main function of the com1+com2 to Com1+com2+com2 (so that the sum is possible), then the result will be different. such as the assignment operator =, subscript operator [], function call operator (), and so on, are not defined as friend operator overloaded functions. The same operator can define multiple operator overloading functions to perform different operations.

Operator overloading functions as a member function of a class
Class Name {    return type operator operator (formal parameter list);} Out-of-class definition format: Return type class Name:: operator operator (formal parameter list) {    function body;}

For member function overloaded operators, there is only one parameter in the parameter table of the binocular operator, and Monocular has no parameters. The same is the overload, why and the friend function in the number of parameters will be different. The reason is that the friend function has no this pointer.

  1. The member function overloads the binocular operator (+)

View Code

For binocular operators, the parameters of an operator overload function are only one parameter, which acts as the right operand of the operator (such as the COM2 object), and the current object is the left operand (such as the COM1 object in the above), which is implicitly passed to the member operator overload function through the this pointer.

  2. member function overloading single-mesh operator (+ +)

View Code

For the monocular operator, the current object is the operand of the operator.

There are several issues to be aware of when using operator overloading:

(1) C + + can only be overloaded with existing C + + operators, do not allow users to define new operators themselves;

(2) Most of the operators in C + + can be overloaded, except for member access operators. The member pointer access operator . *, scope operator ::, length operator sizeof , and conditional operator ? :;

(3) The number of operands (operands) of an operator cannot be changed after overloading. For example: "+" is an operator that implements two operands, and is still a binocular operator after overloading;

(4) Overloading cannot change the precedence of the operator;

(5) Overloading cannot change the properties of an operator's original combination. For example: Z=x/y*a, the execution is the first to do the left combination of arithmetic X/y, after overloading is so, will not become the first right to combine y*a;

(6) Operator overloading cannot be all predefined basic data in C + + and is intended to prevent users from modifying the nature of the operators used for basic type data;

(7) From the above example, you can see that the binocular operator can be overloaded as a friend function can also be overloaded to member functions, but there is a situation, can only make the UF meta-function, what is the situation? As an example:

View Code

If we change the total=com1+5 of the main () principal function in the above section to TOTAL=5+COM1, then the program will error (there is no "+" operator that matches these operands) because the left operand 5 is not an object of that complex number. You cannot call the corresponding member function complex operator+ (int x), so the compilation error. But if we define a two-friend function, we can solve the above problem:

1 friend Complex operator+ (Complex com1, int x); 2 friend Complex operator+ (int x, Complex com1);

The complete program is:

View Code

The operator overload of C + + also made a complete program test with the following results:

  

"Pre" and "post" problems in operator overloading and operator <<, >> overloads

In the preceding, the C + + operator overload function is described. After looking at the example of the single-eye operator (+ +) overload, some friends might ask the question: the + + increment operator can be placed either before the operand or after the operand in C or C + +, but the pre and post effects are completely different (Q-front operator: Add 1 First, then assign value ; Post operator: Assign first, plus 1). So how do you overload them to differentiate effectively? Today we'll look at how the overloads of the pre-and post-operators are handled in C + +. And an overload that introduces the insert operator (>>) and the extract operator (<<).

In C + +, the compiler distinguishes a predecessor or a post operation by inserting the keyword int in the operator's overloaded function parameter table.

See procedure:

View Code

Results:

  

It is clear from the example code that the Post operator overload function has an int type parameter than the predecessor operator overload function, which is just to differentiate the predecessor and post operators, and it has no effect. Therefore, an argument of type int can take any value when the post-operator overload function is called.

Operator << and >> overloads

In C + +, the operator "<<" and ">>" are defined as the left and right displacement operators. Because they are overloaded in the iostream header file, they can be used for the output and input of basic data.

View Code

Results:

  

The insert operator "<<" is the binocular operator, the left operand is the object of the output stream class Ostream, and the right operand is the system-predefined base type data. Header file Iostrem Its overloaded function prototype is ostream& operator<< (ostream&, type name); The type name refers to the basic type data. However, if you want to output user-defined type data, you need to overload the operator "<<" because the operator's left operand must be an object of the Ostream class, so the insert operator "<<" can only be a friend or normal function of a class, and cannot be a member function of another class. General definition Format:

ostream& operator<< (ostream&, custom class name &);

The extraction operator ">>" is also the case, the left operand is an object of the IStream class, and the right operand is the base type data. Header file Iostrem Its overloaded function prototype is istream& operator>> (istream&, type name), and the extract operator cannot be a member function of another class, either a friend function or a normal function. Its general definition format is:

istream& operator>> (istream&, custom class name &);

We also use the complex class (plural class) of the previous section to give an example:

View Code

Results:

  

Operator Overloading Reference Example

Post C + + operator Overloading Summary provides an example of some commonly used operator overloads:

General operator overloadingView CodeRelational operator overloadingView CodeLogical operator overloadingView CodeMonocular operator OverloadingView CodeIncrement operator overloadView CodeBitwise operator OverloadingView CodeAssignment operator overloading

There is no "=".

View CodeMemory operator overloadingView CodeSpecial operator overloadingView Code

These can only be overloaded in the form of a friend function:

1 friend inline ostream &operator << (ostream&, a&);//output stream 2 friend inline IStream &operator >> (Istream&, a&);//input stream

  More content to add later ...

Operator overloading operator

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.