C + + about operator overloading

Source: Internet
Author: User

Reprint Source: http://c.biancheng.net/cpp/biancheng/view/216.html

The functions of the

Overloaded operators are generally format as follows:
    function type operator operator name (formal parameter list)
    {
       //overload handling of Operators
   }

For example, to use "+" for the addition of complex classes (complex numbers), the prototype of the function can be:
& nbsp   Complex operator+ (complex& c1, complex& C2);
in the general format above, operator is the keyword, which is a function specifically for defining overloaded operators, and the operator name is the predefined operator that C + + provides to the user. Note that the function name is made up of operator and operators, and the above operator+ is the function name, which means "to operator + overload". With this in mind, you can see that there is no difference in formality between such functions and other functions. The two parameter is a reference to the complex class object and requires that the argument be an complex class object.

After the function that defines the overloaded operator, you can say that the function operator + overloads the operator +. When executing the expression C1 + C2 of the complex number addition (assuming that both C1 and C2 are defined as complex class objects), the system calls the operator+ function, C1 and C2 as arguments, and the actual combination of the parameters.

to illustrate that after operator overloading, executing an expression is the process of invoking a function, you can add two integers and imagine calling the following function:
int operator + (int a, int b)
{
    return (A+B);
}

If there is an expression 5+8, call this function, with 5 and 8 as the arguments when the function is called, the return value of the function is 13. This is the method of using the function to understand the operator. You can overload the operator "+" on the basis of the example 10.1 program to add it to the complex number.

[Example 10.2] Overrides example 10.1, overloading the operator "+" so that it can be used to add two complex numbers.

  1. #include <iostream>
  2. Using namespace std;
  3. Class Complex
  4. {
  5. Public:
  6. Complex( ){Real=0; imag=0;}
  7. Complex(double R,double i){real=r; imag=i;}
  8. Complex operator+ (Complex &c2); Functions that declare overloaded operators
  9. void display( );
  10. Private:
  11. double real;
  12. double imag;
  13. };
  14. Complex Complex::operator+ (Complex &c2) //functions that define overloaded operators
  15. {
  16. Complex c;
  17. C. Real=real+c2. Real;
  18. C. imag=imag+c2. Imag;
  19. return c;
  20. }
  21. void Complex::display( )
  22. {
  23. cout<<"("<<real<< ","<<imag<<"i)"<<endl ;
  24. }
  25. int main( )
  26. {
  27. Complex C1(3,4),C2(5,-ten), C3;
  28. C3=c1+c2; //operator + for complex operations
  29. cout<<"c1="; C1. Display( );
  30. cout<<"c2="; C2. Display( );
  31. cout<<"c1+c2="; C3. Display( );
  32. return 0;
  33. }

The result of the operation is the same as example 10.1:
C1= (3+4i)
C2= (5-10i)
C1+c2= (8,-6i)

Please compare example 10.1 and example 10.2 with only two differences:
1) In Example 10.2, the operator+ function replaces the Complex_add function in example 10.1, and only the function names are different, the functions and function return values are the same type.

2) in the main function, take "C3=C1+C2;" Replaces the "C3=c1.complex_add (C2);" in example 10.1. After the operator + is overloaded as a member function of a class, the C + + compilation system interprets the expression C1+C2 in the program as
c1.operator+ (C2)//where C1 and C2 are objects of the complex class
That is, the operator overload function operator+ (Complex &AMP;C2) called C1 with C2 as the argument, is evaluated and the sum of the two complex numbers is obtained.

As you can see, the structure and execution of the two programs are basically the same, with the same effect and the same results. The overloaded operator is implemented by the corresponding function. One might say, in that case, why overload the operator? We want to look at the problem from the user's point of view, although the functions implemented by overloaded operators can be fully implemented with functions, using operator overloading makes the user program easy to write, read, and maintain. In practice, the declaration of classes and the use of classes are often separated. If in declaring the complex class, the operator +,-, *,/are overloaded, then users of this class can be programmed to completely regardless of how the function is implemented, be assured that the direct use of the +,-, *,/The operation of complex numbers can be very convenient.

The above operator overload function operator+ can also be rewritten more concisely:
Complex Complex::operator + (Complex &c2)
{return Complex (real+c2.real, imag+c2.imag);}
The complex (Real+c2.real, Imag+c2.imag) in the return statement is a temporary object that has no name and is a nameless object. The constructor is called during the creation of a temporary object. The return statement returns the temporary object as a function value.

Consider whether you can add a constant and a complex object in example 10.2. Such as
C3=3+C2; Error, mismatch with formal parameter type
Should be written in the form of an object, such as
C3 = Complex (3,0) +c2; Correct, type is Object

It is necessary to note that, after the operator is overloaded, its original functionality remains intact, without loss or alteration. By operator overloading, the scope of the existing operators of C + + is expanded to make them available to class objects.

Operator overloading is important for C + +, combining operator overloading with classes to define new data types that are useful and easy to use in C + + programs. Operator overloading makes C + + more powerful? Better extensibility and adaptability, which is one of the most appealing features of C + +.

C + + defines the following rules for operator overloading.

1) C + + does not allow users to define new operators themselves.can only overload an existing C + + operator。 For example, some people find it convenient to use "* *" as the power operator in basic, and to define "* *" as the power operator in C + + and "3**5" to represent 35, which is not possible.

2) overload does notcan change the number of operator operands (that is, shoving count)。 such as the relational operator ">" and "<" are binocular operators, which are still binocular operators after overloading, require two parameters. Operators "+", "-", "*", "&" can be either single-mesh operators or binocular operators, which can be overloaded as single-or binocular operators, respectively.

3) Heavy DutyThe precedence level of an operator cannot be changed。 For example, "*" and "/" take precedence over "+" and "-", regardless of how they are overloaded, the precedence level between the operators does not change. Sometimes in a program you want to change the precedence of an operator, and you can only use parentheses to force the order of operations of overloaded operators to change.

4) Heavy Dutycannot change the binding of operators。 If the assignment operator is right-associative (from right to left), it is still right-associative after overloading.

5) functions for overloaded operatorscannot have default parameters, otherwise the number of operator parameters is changed, which contradicts the preceding point (2).

6) Overloaded operators must be used with objects of user-defined custom types.at least one of its parameters should be a class object(or a reference to a class object). That is, parameters cannot be all standard C + + types to prevent users from modifying the nature of the operators used for standard type data, as follows:
int operator + (int a,int b)
{
Retum (A-B);
}
The effect of the original operator + is to add two numbers, now attempting to change its function to two number subtraction by overloading. If this overload is allowed, if there is an expression 4+3, does it result in 7 or 1? Obviously, this is absolutely forbidden.

If there are two parameters, both of these parameters can be class objects, one is a class object, and the other is a C + + standard type of data, such as
Complex operator + (int a,complex&c)
{
Return Complex (a +c.real, c.imag);
}
Its purpose is to make an integer and a complex number Add.

7) Operators for class objects generally must be overloaded, with two exceptions,operator "=" and "&" do not have to be overloaded。

The ① assignment operator (=) can be used for each class object and can be leveraged to assign values to each other in a homogeneous object. We know that an assignment operator can be used to assign a value to an object of a class, because the system has overloaded an assignment operator for each newly declared class, and it does so by copying the data members of the class one by one. The user can assume that it is the default object assignment operator provided by the system and can be used directly for assignment between objects without overloading themselves. However, sometimes the default object assignment operator provided by the system does not meet the requirements of the program, for example, when a data member contains a pointer member that points to dynamically allocated memory, there can be a danger when replicating this member. In this case, you need to overload the assignment operator yourself.

The ② address operator & does not have to be overloaded, it returns the start address of the class object in memory.

8) Theoretically, you can overload an operator to perform arbitrary operations, such as overloading an addition operator with information from an output object, and overloading the ">" operator with a "less than" operation. But this violates the original intention of operator overloading, instead of mentioning the readability of the GAO, it makes people inexplicably, unable to understand the program. Overloaded operators should be functionally similar to the functions that the operator implements when it acts on standard type data (for example, "+" to implement addition, and ">" to achieve "greater than" relational operations).

9) Operator overloading functioncan be a member function of a class, or it can be a friend function of a class, it can also be a non-class member function and not a friend.Common Functions。

C + + about 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.