Operator Overloading in C ++

Source: Internet
Author: User

The so-called overload is to give a new meaning. Function Overloading is to assign a new meaning to an existing function to implement new functions.
Operators can also be overloaded.. Operator Overloading gives multiple meanings to existing operators...

 

// That is to say, after the overload is completed, the method that best matches the call will be automatically called according to the overload function we define... for example, the overload operator + of the class we define. when we use the class object addition, the overload we define will be automatically called... when we use the built-in + method operation, such as int B = 5 + 3, we still call the built-in + method operation for processing ..

In C ++, the pre-defined operator can only operate on basic data types, but does not apply to user-defined types (such as classes ).

// Same as above, built-in operators can only be applied to built-in data types... such as int char double.

(1) c ++ does not allow users to define new operators themselves. It can only overload existing C ++ operators.

// That is to say, only built-in +-*/and other operators can be reloaded, and operator computation cannot be created by yourself. .

(2) The vast majority of operators in the C ++ operator C ++ that allow overloading are allowed.
There are only five operators that cannot be overloaded:
(1) member access operators.
(2) Scope operator limit
(3) conditional operators? :
(4) member pointer operator *
(5) Compile the start symbol of the preprocessing command #

(3) The number of operators (that is, the number of operands) cannot be changed during the overload operation.

// The operator operation object cannot be changed. For example, the + operator has two operands. When we reload the operator, we can only have two operands.

(4) Overloading cannot change the priority of operators.

// After reload is completed, the priority level of the function cannot be changed, for example, the + number. No matter how you design the overload function, it will never be higher than the () Priority ......
(5) Functions with heavy-duty operators cannot have default parameters. Otherwise, the number of operator parameters is changed, which is in conflict with the preceding (3.

// Same as above 3.

(6) The overloaded operator must be used together with a user-defined custom object. Its Parameter must have at least one class Object (or Class Object reference ). That is to say, parameters cannot all be standard types of c ++ to prevent users from modifying the properties of operators used for standard data.

// The overloaded parameters cannot all be c ++ built-in data types. At least one custom type is required. Because if we define two built-in types, they will conflict with those defined by the system. Because when we use built-in operators, the compiler is actually calling an overload operator for computation. This is automatically added by the compiler. If we have the same definition, a conflict will occur.

(7) The operators used for class objects must be reloaded, but there are two exceptions. The operators "=" and "&" do not need to be reloaded.
① The Value assignment operator (=) can be used for every class object and can be used to assign values to each other among similar objects.
② The address operator does not need to be overloaded. It can return the starting address of the class object in the memory.

// As mentioned earlier, the C ++ built-in operator can only calculate the built-in data type. So when we want to use a custom type, we must reload it ..

In short, when the original operator of C ++ is overloaded, its original semantics does not disappear, which is equivalent to defining a new operator for a specific class.
You can use member functions and friend functions to overload operators. You can refer to the following experiences:
(1) operators that can only be overloaded by member functions include =, (), [],->, new, and delete.
(2) it is best to reload a single object operator as a member function.
(3) compound assignment operators such as + =,-=, * =,/=, & =, and ,! = ,~ =, % =, >=, <=We recommend that you reload the function as a member function.
(4) For other operators, we recommend that you reload them as friend functions.
The method to overload operators is to define a function that overload operators. When you need to execute an overloaded operator, the system automatically calls this function to implement corresponding operations. That is to say, Operator Overloading is implemented by defining functions. Operator Overloading is essentially a function overloading. The Function Format of the overload operator is as follows:
Operator name of function type (table of parameters)
{
Reload operator Processing
}
When the reload is a class member function, the number of parameters = the number of original operations-1
(Except for + + and -- On the rear)

// When the overload is a class member function, the number of parameters equals to the original operand-1 .. for example, object A + object B .. we need two operands A and B for reload, but we can pass the previous one. For example, we only need to pass B to a + B. Because when calling the overload operator is the overload operator called by a, it is the current object and it is the this pointer .. And the class member function can only use two class members...

When the overload is a friend function, the number of parameters = the number of original operations, and at least one custom type parameter should exist.

// It is not much different from the above, but it can call non-class objects .. for example, call an object A + 1 .. note that even if it is defined as a friend function, its operands must have a custom type.

 

View an instance:

# Include <iostream>
Using namespace STD;
Class complex // plural class declaration
{
Public: // external interface
Complex (double r = 0.0, double I = 0.0)
{
Real = R;
Imag = I;
} // Constructor
Complex operator + (complex C2); // + reload as a member function
Complex operator-(complex C2); //-Reload as a member function
Void display (); // The plural value of the output.
PRIVATE: // Private Data Member
Double real; // real part of the plural number
Double imag; // The Plural imaginary part.
};
Complex complex: Operator + (complex C2) // overload function implementation
{
Complex C;
C. Real = real + c2.real;
C. imag = imag + c2.imag;
Return complex (C. Real, C. IMAG );
}
Complex complex: Operator-(complex C2) // overload function implementation
{
Complex C;
C. Real = real-c2.real;
C. imag = imag-c2.imag;
Return complex (C. Real, C. IMAG );
}
Void complex: Display ()
{Cout <"(" <real <"," <imag <"I" <")" <Endl ;}

 

Int main () // Main Function
{
Complex C1 (5, 4), C2 (2, 10), C3; // the object that declares the plural class
Cout <"C1 ="; c1.display ();
Cout <"C2 ="; c2.display ();
C3 = c1-c2; // perform the complex Subtraction using the overload Operator
Cout <"C3 = c1-c2 = ";
C3.display ();
C3 = C1 + C2; // use the overload operator to complete the plural Addition
Cout <"C3 = C1 + C2 = ";
C3.display ();
System ("pause ");
Return 0;
}

ProgramThe output result is:
C1 = (5, 4I)
C2 = (2, 10i)
C3 = c1-c2 = (3,-6i)
C3 = C1 + C2 = (7, 14i)

PassCodeWe can see that two member function overload operators are defined .. the + and -. when we use the two Members of this class for addition or subtraction, the overloaded operators will be automatically called .. use the operations defined in the overload operator. Then we can see that when we perform the + or-operation, we add or subtract the values of the complex numbers saved in the two objects and return them. Note that not the + and minus signs are completely changed, but the objects in this class call the overload only when performing the +-operation.

Let's test it. In the main () function, we define three more variables, int A = 5, B = 3, C; C = A-B; then output the value of C. We find that the output is 2 .. this also proves that the defined overload operator does not change its original function .. it gives it multiple meanings ..

Then let's take a look at the use of Operator Overloading in youyuan functions.

We only need to implement the complex: Operator + (complex C2) // overload Function
{
Complex C;
C. Real = real + c2.real; // real represents this-> real actually represents the current object passed in.
C. imag = imag + c2.imag;
Return complex (C. Real, C. IMAG );
}

Modify this code... to complex friend complex: Operator + (complex C2 complex C3)

The same functions can also be completed .. it is also easier to expand .. because I learned from the above .. the overloaded operator must be used with a User-Defined Object of the custom type. that is to say, there must be at least one custom type .. or its reference .. if we use the member operator overload, we can only use the object members in the class .. we can use data outside the class if you use the youyuan operator to overload it .. you can directly change it to complex friend complex: Operator + (complex C2 int A) when you need it.

Related Article

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.