C + + operator overload explanation and classic example __c++

Source: Internet
Author: User
Tags arithmetic arithmetic operators logical operators mul

The operations object of a predefined operator in C + + can only be a basic data type, and in fact, a similar operation is required for many user-defined types. For example:
Class Complex
{
Public
Complex (double r=0.0,double i=0.0) {real=r;imag=i;}
void display ();
Private
Double Real;
Double imag;
};
Complex A (10,20), B (5,8);
How the "a+b" operation is implemented. At this time we need to write our own program to illustrate "+" in the role of the complex class object, the implementation of what kind of function, this is operator overloading. Operator overloading is assigning multiple meanings to an existing operator, so that the same operator acts on different types of data causing different types of behavior.
The essence of operator overloading is function overloading. In the implementation process, the specified operational expression is first converted to the operator function call, the operation object into the operator function of the argument, and then according to the type of argument to determine the need to call the compliance function, this process love the compilation process completed.

One,rules for operator overloading
Operator overloading rules are as follows:
①, C + + operators can be overloaded except for a few, and can only overload existing operators in C + +.
The precedence and binding of operators after ② and overloads do not change.
③, operator overloading is an appropriate modification of the original operator for the actual needs of the new type of data. In general, overloaded functionality should be similar to the original function, you cannot change the number of operations on the original operator, at least one Action object is a custom type.
There are only five operators that cannot be overloaded: the member operator ".", The pointer operator "*", The scope Operator::, "sizeof", the conditional operator. :”。
There are two types of operator overloading forms, which are overloaded as member functions of the class and as friend functions of the class.
The general grammatical form of operator overloading for a member function of a class is:
function type operator operator (formal parameter list)
{
function body;
}
Operator overloading is the general grammatical form of a friend function of a class:
Friend function type operator operator (formal parameter list)
{
function body;
}
Where the function type is the result type of the operation; operator is the keyword that defines the operator overloaded function; the operator is the overloaded operator name.
When an operator is overloaded with a member function of a class, the function has one less number of arguments than the original operand, and the number of arguments is the same as the number of original operands when overloaded as a friend function of a class. The reason is that when overloading a member function of a class, if an object uses overloaded member functions, its own data can be accessed directly, without having to be passed in the parameter table, and the operand is the object itself. When overloading is a friend function, the friend function operates on the data of an object, and the object's name must be passed, so the parameters used are passed and the number of operands is not changed.
The primary advantage of operator overloading is that it allows you to change the operation of the operators used inside the system to accommodate similar operations of user-defined types.

Second,operator overloading is a member function
For the binocular operator B, if you want to overload B as a member function of a class to enable it to implement the expression Oprd1 b oprd2, where Oprd1 is an object of Class A, you should overload B with a member function of Class A, which has only one formal parameter, and the type of the formal parameter is the type of the Oprd2. After overloading, the expression Oprd1 b oprd2 is the equivalent of a function call Oprd1.operator B (OPRD2).
For a forward single operator U, such as "-" (minus), if you want to overload u as a member function of a class to implement the expression U OPRD, where OPRD is an object of Class A, you should overload the member function of Class A and the function has no formal parameters. After overloading, the expression U oprd corresponds to the function call Oprd.operator u ().
For the back operator "+ +" and "--", if you want to overload them as member functions of a class to implement an expression oprd++ or oprd--, where the OPRD is an object of Class A, the operator should be overloaded with a member function of Class A, when the function takes an integer parameter. After overloading, expressions oprd++ and oprd-want to be in function calls oprd.operator++ (0) and oprd.operator-(0);
Operator overloading is giving multiple meanings to an existing operator. By redefining the operator so that it can be used to perform specific functions on objects of a particular class, this enhances the ability of the C + + language to expand.

1. The role of operator overloading:

Operator overloading allows the C + + operator to have a user-defined meaning on a user-defined type (Class). Overloaded operators are the syntax adornments of function calls:

Class Fred

{

Public

// ...

};

#if 0

No operator Overload:

Fred Add (Fred, Fred);

Fred Mul (Fred, Fred);

Fred F (Fred A, Fred B, Fred C)

{

Return Add (Add (Mul (a,b), Mul (B,c)), Mul (C,a)); Haha, how ridiculous ...

}

#else

Operator Overload:

Fred Operator+ (Fred, Fred);

Fred Operator* (Fred, Fred);

Fred F (Fred A, Fred B, Fred C)

{

Return a*b + b*c + c*a;

}

#endif

2. An operator that can be used as an overload:

Arithmetic operator: +,-, *,/,%,++,--;

Bitwise operator Operator: &,|,~,^,< <,> >

Logical operators:!,&&,| |;

Comparison operators: <,>, >=,<=,==,!=;

Assignment operator: =,+=,-=,*=,/=,%=,&=,|=,^=,< <=,> >=;

Other operators: [], (),->,, (comma operator), new,delete,new[],delete[],->*.

The following operators do not allow overloading:

.,.*,::,?:

3. After operator overloading, precedence and binding:

The user overloads the new defined operator without altering the precedence and binding of the original operator. This means that operator overloading does not change the precedence and binding of operators, and operator overloading does not change the syntax structure of operators, that is, the single order operator can only be overloaded as a monocular operator, and the binocular operator can only overload the binocular operators.

4. How the compiler chooses which operator function to use:

Operator overloading is actually a function, so an overload of an operator is actually an overload of a function. The compiler's choice of operator overloading follows the selection principle of function overload. When a less obvious operation is encountered, the compiler will look for the operator function that the parameter matches.

5. What are the limitations of overloaded operators:

(1) No new operator can be coined. Overloaded operators must be restricted to overloaded operators within the range of operators already in the C + + language.

(2) Overloaded operators adhere to 4 "Cannot change".

• The number of operator operands cannot be changed;

• The original precedence of the operator cannot be changed;

• Cannot change the original binding of operators;

• The original syntax structure of the operator cannot be changed.

6. What principles must be followed for operator overloading:

Operator overloading makes the program more concise, makes the expression more intuitive, and increases readability. However, operator overloading should not be used too much, otherwise it will cause some trouble.

(1) The meaning of the overloaded operator must be clear.

(2) Overloaded operators cannot have two semantics.

Two forms of operator overloaded functions

Operators overloaded functions generally take the following two forms: member function form and friend function form. Both forms have access to private members in the class.

1. overload as a member function of a class

Here is an example of a arithmetic character that overloads the plural with a plural operation. Complex numbers are constructed from real and imaginary parts, and you can define a complex number class and then overload complex arithmetic operators in the class. First look at the following source code:

#include

Class Complex

{

Public

Complex () {real=imag=0;}

Complex (double R, double i)

{

Real = r, imag = i;

}

Complex operator + (const complex &c);

Complex operator-(const complex &c);

Complex operator * (const complex &C);

Complex operator/(const complex &C);

friend void print (const complex &c);

Private

Double real, imag;

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.