Concepts and syntax for C + + learning 26 operator overloading

Source: Internet
Author: User

The so-called overloading, is to give new meaning. function overloading allows a function name to have multiple functions and perform different operations under different circumstances. Operator overloading (Operator overloading) is also a reason that the same operator can have different functions.

In fact, we have unknowingly used operator overloading. For example, the "+" number can be added to data of different types (int, float, and so on); "<<" is both the displacement operator and the output data to the console with cout. These operators have been overloaded by C + +.

C + + also allows programmers to overload operators themselves, which brings us a lot of convenience.

The following code defines a complex number class that, with operator overloading, implements the addition of complex numbers with the "+" sign:

#include <iostream>using namespacestd;classcomplex{Private:    DoubleReal//Real Department    DoubleImag//Imaginary Part Public: Complex (): Real (0.0), Imag (0.0) {} complex (DoubleADoubleb): Real (a), imag (b) {} complexoperator+(ConstComplex & A)Const; voidDisplay ()Const;};//operator OverloadingComplex complex::operator+(ConstComplex & A)Const{complex B; B.real= Real +A.real; B.imag= Imag +A.imag; returnB;}voidComplex::d Isplay ()Const{cout<<real<<" + "<<imag<<"I"<<Endl;}intMain () {Complex C1 (4.3,5.8); Complex C2 (2.4,3.7);    Complex C3; C3= C1 +C2;      C3.display (); return 0;}

The above code defines a complex number class, real represents the real part, Imag represents the imaginary part, the 11th line declares the operator overload, and the 16th line is defined. Careful observation of these two lines of code can be found to be very similar to function overloading.

Operator overloading is defined as a function that implements the desired function in the body of the function, which is automatically called by the compiler when the operator is used. In other words, operator overloading is implemented through function definitions, which are essentially function overloads.

The format of operator overloading is:

operator operator name (formal parameter table column) {    //TODO:}

Operator is a keyword that is specifically used to define the functions of overloaded operators. For example, to overload "+" at the global scope to implement complex addition operations, you can define:

operator+ (constconst Complex &B) {    complex C;     = A.real + b.real;     = A.imag + b.imag;     return C;}

Careful observation can be found that the function name is composed of operator and operators, the above "operator+" is the function name. The functions of overloaded operators have a specific format except for the function name, and there is no difference between the other and the normal functions.

In the example above, we overloaded the operator "+" in class Complex, which is only valid for Complex objects. When the c3 = c1 + c2; statement is executed, the compiler detects the left side of the "+" sign (the "+" sign has a left-associative) is a Complex object that invokes the operator overload function, which is converted to:

C1. operator+ (C2);

is obviously a function call.

The above operator overloads can also be defined in a more concise form:

Complex complex::operator+ (const Complex & A)const{    return Complex (Real+a.real, imag+a.imag);}

complex(real+A.real, imag+A.imag)a temporary object is created in the return statement, which has no object name and is an anonymous object. The constructor is called during the creation of the temporary object, and the return statement returns the temporary object as a function return value.

Although the functions implemented by overloaded operators can be completely substituted with functions, operator overloading makes the writing of the program more user-friendly and easy to read. After the operator is overloaded, the original functionality remains intact, without loss or change. Operator overloading expands the functionality of the existing operators in C + + to make them available to class objects.

Rules for overloaded operators

C + + has many limitations on operator overloading.

1) First, not all operators can be overloaded. The operators that can be overloaded include:
+-*/% ^ & |  ~  ! = < > + = = *=/=%= ^= &= |=
<< >> <<= >>= = = = <= >= && | | + +--,->* () []
New new[] Delete delete[]

In the above operator, [] is the subscript operator, () is the function call operator. Both the pre-and post-form of the self-increment operator can be overloaded. The length operator "sizeof", The conditional operator ":?", the member selector ".", the object selector ". *" and the domain resolution operator:: "cannot be overloaded.

In the above operator, [] is the subscript operator, () is the function call operator. Both the pre-and post-form of the self-increment operator can be overloaded. The length operator "sizeof", The conditional operator ":?", the member selector ".", the object selector ". *" and the domain resolution operator:: "cannot be overloaded.

2) overloading cannot change the precedence and binding of operators. Assuming that the "+" and "*" numbers are overloaded in the complex class in the previous section, the following code:

int Main () {    complex c1,c2,c3,c4;     = C1 + C2 * c3;     return 0 ;}

c4 = c1 + c2 * c3;Statements are equal to the c4 = c1 + ( c2 * c3 ) ; multiplication priority is still higher than the addition, and they are still two-dollar operators.

3) overloading does not change the use of operators, such as the "+" sign always appears between two operands, and must be so after overloading.

4) A function that overloads an operator cannot have a default argument, or it changes the number of operator operands, which is obviously wrong.

Concepts and syntax for C + + learning 26 operator overloading

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.