Definition and Summary of C + + main operator overloading

Source: Internet
Author: User
Tags arithmetic operators mul

The operands of predefined operators in C + + can only be basic data types, and in fact, for many user-defined types, similar operations are Required. 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 is the "a+b" operation implemented? At this point we need to write our own program to illustrate what function the "+" implements when acting on the complex class object, which is operator overloading. Operator overloading is to give multiple meanings to an existing operator, causing different types of behavior for the same operator to work on different types of Data.
The essence of operator overloading is function overloading. In the implementation process, the specified operation expression is converted into a call to the operator function, the operand is converted to the argument of the operator function, and then according to the type of the argument to determine the need to call the compliance function, this process love the completion of the compilation Process.

first,rules for operator overloading
The operator overloading rules are as follows:
Operators in ①, C + + are all overloaded except for a few, and can only overload existing operators in C + +.
The precedence and binding of operators after ② and overloading do not change.
③, operator overloading is the actual need for the new type of data, the original operator is modified APPROPRIATELY. In general, the functionality of overloading should be similar to the original function, cannot change the number of operands of the original operator, and 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, overloading the member functions of the class and overloading the friend function for the class.
The general syntax for operator overloading for member functions of a class is:
function type operator operator (formal parameter List)
{
function body;
}
The general syntax for operator overloading for a friend function of a class is:
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 overload function; the operator is the overloaded operator Name.
When an operator is overloaded as a member function of a class, the number of arguments to the function is less than the number of previous operations, and when overloaded with a friend function of a class, the number of arguments is the same as the number of original OPERANDS. The reason is that when you overload a member function for a class, if an object uses an overloaded member function, its own data can be accessed directly, it is not required to be passed in the parameter table, and the fewer operands are the object itself. While overloading is a friend function, the friend function operates on the data of an object, which must be done by the name of the object, so the parameters used are passed, and the number of operands is not changed.
The main advantage of operator overloading is that it allows you to change the operation of operators that are used inside the system to accommodate similar operations of user-defined Types.

second,operator overloading is a member function
For binocular operator b, if you want to overload B as a member function of a class so that it can implement an expression Oprd1 B oprd2, where Oprd1 is an object of class a, you should overload B as a member function of class a, which has only one formal parameter, and the type of the formal parameter is the type that the oprd2 belongs to. After overloading, the expression Oprd1 b oprd2 is equivalent to a function call Oprd1.operator b (oprd2).
For the OPRD operator u, such as "-" (minus), if you want to overload the member function of U as a class to implement the expression u, where OPRD is an object of class a, you should overload the member function of class a, the function has no formal parameters. After overloading, the expression U OPRD is equivalent to the function call Oprd.operator u ().
For the post operator "+ +" and "--" if you want to overload them as member functions of a class to implement an expression oprd++ or oprd--, where OPRD is an object of class a, then 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 called as function calls oprd.operator++ (0) and oprd.operator-(0);
Operator overloading is the multiple meaning given to an existing Operator. By redefining the operator so that it can be used for specific classes of objects to perform specific functions, 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 syntax decorations for function calls:

Class Fred

{

Public

// ...

};

#if 0

No operator overloads:

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

There are operator overloads:

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 operators: +,-, *,/,%,++,--;

Bitwise manipulation Operators: &,|,~,^,< <,> >

Logical operators:!,&&,| |;

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

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 changing the precedence and binding of the original Operator. This means that operator overloading does not change the precedence and binding of operators, and the operator overloads do not change the syntax structure of the operator, that is, the Single-mesh operator can only be overloaded to a single-mesh operator, and binocular operators can only overload the binocular Operator.

4. How to choose which operator function to compile the program:

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

5. What are the limitations of overloaded operators:

(1) The new operator cannot be figment. Overloaded operators must be restricted to the allowed overloaded operators in 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 precedence of the operator cannot be changed;

• The original binding of the operator cannot be changed;

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

6. Which principles must be followed when operator overloading:

Operator overloading can make the program more concise, making the expression more intuitive and more readable. however, the use of operator overloading should not be too much, otherwise it will cause some trouble.

(1) the meaning of overloaded operators must be clear.

(2) overloaded operators cannot have two Semantics.

Two forms of operator overloaded functions

Operator overloading functions generally take the form of member functions and friend functions in the following two forms: Both of these forms can access private members in the CLASS.

1. overloading a member function for a class

Here is an example of a arithmetic character that overloads a complex number for complex operations. Complex numbers are constructed from real and imaginary parts, you can define a complex number class, and then overload the operator of complex arithmetic in a class. Let's 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;

};

Inline complex complex::operator + (const complex &c)

{

Return complex (real + c.real, Imag + c.imag);

}

Inline Complex Complex::operator-(const Complex &c)

{

Return complex (real-c.real, imag-c.imag);

}

Inline Complex Complex::operator * (const complex &c)

{

Return Complex (real * C.real-imag * c.imag, real * c.imag + imag * c.real);

}

Inline Complex Complex::operator/(const Complex &c)

{

Return Complex (real * c.real + imag + c.imag)/(c.real * c.real + c.imag * c.imag),

(imag * c.real-real * c.imag)/(c.real * c.real + c.imag * c.imag));

}

void Print (const complex &c)

{

If (c.imag<0)

cout<

Else

cout<

}

void Main ()

{

Complex C1 (2.0, 3.0), C2 (4.0, -2.0), c3;

C3 = C1 + c2;

cout<< "/nc1+c2=";

Print (c3);

C3 = c1-c2;

cout<< "/nc1-c2=";

Print (c3);

C3 = C1 * c2;

cout<< "/nc1*c2=";

Print (c3);

C3 = c1/c2;

cout<< "/nc1/c2=";

Print (c3);

C3 = (c1+c2) * (c1-c2) * c2/c1;

cout<< "/n (c1+c2) * (c1-c2) *c2/c1=";

Print (c3);

cout<

}

The result of this program is:

C1+c2=6+1i

c1-c2=-2+5i

c1*c2=14+8i

c1/c2=0.45+0.8i

(c1+c2) * (c1-c2) *c2/c1=9.61538+25.2308i

In the program, class complex defines 4 member functions as operator overloading Functions. The operator overloaded function is described as a member function of the class as Follows:

Class name > operator operator > (parameter Table)

Where operator is the keyword that defines operator overloading Functions.

An expression that appears in the Program:

C1+c2

The compiler will interpret it as:

c1.operator+ (c2)

of these, C1 and C2 are objects of the complex class. Operator+ () is an overloaded function of operation +.

The operator overload function has only one parameter, c2. visible, when overloaded to member functions, the binocular operator has only one parameter. For the Monocular operator, the parameter cannot be explicitly described when overloaded as a member Function. When overloaded as a member function, there is always a parameter implied, and the parameter is the this pointer. The this pointer is a pointer to the object that invokes the member Function.

2. overloading is a friend function:

An operator overload function can also be a friend Function. When you overload a friend function, there is no implied parameter of the This Pointer. thus, The pair binocular operator, the friend function has 2 parameters, the monocular operator, the friend function has a parameter. however, Some operators cannot be overloaded as friend functions, which are: =, (), [], and->.

The overload function for an operator overloaded with a friend function is defined in the following format:

Friend type specifier > operator operator > (parameter Table)

{......}

The following UF meta-function code member functions, overloads to write the above example, the program is as Follows:

#include

Class Complex

{

Public

Complex () {real=imag=0;}

Complex (double r, Double I)

{

Real = r, Imag = i;

}

Friend complex operator + (const complex &c1, const complex &c2);

Friend Complex Operator-(const complex &c1, const complex &c2);

Friend Complex operator * (const complex &c1, const complex &c2);

Friend Complex Operator/(const complex &c1, const complex &c2);

Friend

void Print (const complex &c);

Private

Double real, imag;

};

Complex operator + (const complex &c1, const complex &C2)

{

Return complex (c1.real + c2.real, C1.imag + c2.imag);

}

Complex Operator-(const complex &c1, const complex &C2)

{

Return complex (c1.real-c2.real, c1.imag-c2.imag);

}

Complex operator * (const complex &c1, const complex &C2)

{

Return Complex (c1.real * C2.real-c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);

}

Complex Operator/(const complex &c1, const complex &C2)

{

Return Complex ((c1.real * c2.real + c1.imag * c2.imag)/(c2.real * c2.real + c2.imag * c2.imag),

(c1.imag * c2.real-c1.real * c2.imag)/(c2.real * c2.real + c2.imag * c2.imag));

}

void Print (const complex &c)

{

If (c.imag<0)

cout<

Else

cout<

}

void Main ()

{

Complex C1 (2.0, 3.0), C2 (4.0, -2.0), c3;

C3 = C1 + c2;

cout<< "/nc1+c2=";

Print (c3);

C3 = c1-c2;

cout<< "/nc1-c2=";

Print (c3);

C3 = C1 * c2;

cout<< "/nc1*c2=";

Print (c3);

C3 = c1/c2;

cout<< "/nc1/c2=";

Print (c3);

C3 = (c1+c2) * (c1-c2) * c2/c1;

cout<< "/n (c1+c2) * (c1-c2) *c2/c1=";

Print (c3);

cout<

}

The program runs the same result as the previous Example. As we have already said, the bitwise operator, when overloaded as a member function, has only one argument and the other is suppressed; when overloaded to a friend function, there are two arguments, no hidden arguments. therefore, the c1+c2 that appear in the program

The compiler is interpreted as:

operator+ (c1, C2)

Call the following function to evaluate the value,

Complex operator + (const Coplex &c1, const complex &C2)

3. Comparison of two types of overloaded forms

In general, the monocular operator is best to be overloaded as a member, the binocular operator is best to be overloaded as a friend function, the binocular operator overload for the friend function as a member function is more convenient for this, however, some binocular operators or overloads for the member function as well, for example, the assignment Operator. because, if it is overloaded as a friend function, there will be places that are inconsistent with the assignment semantics. Overloaded examples of other operators

1). subscript operator Overloading

Because the C language array does not hold its size, it is not possible to check the access range of the array elements, and there is no guarantee that the dynamic assignment of the arrays will not cross the Boundary. A class of C + + allows you to define a more secure, powerful array type. To do this, define the overloaded operator [] for the class.

Here's an example:

#include

Class Chararray

{

Public

Chararray (int L)

{

Length = l;

Buff = new char[length];

}

~chararray () {delete Buff;}

int GetLength () {return Length;}

Char & operator [] (int i);

Private

int Length;

char * Buff;

};

Char & chararray::operator [] (int i)

{

static char ch = 0;

If (i =0)

Return buff[i];

Else

{

cout<< "/nindex out of range.";

Return ch;

}

}

void Main ()

{

int cnt;

Chararray string1 (6);

char * string2 = "string";

For (cnt=0; cnt<8; Cnt++)

string1[cnt] = string2[cnt];

cout<< "/n";

For (cnt=0; cnt<8; Cnt++)

cout<

cout<< "/n";

cout<

}

The advantages of this array class are as Follows:

(1) its size is not necessarily a constant.

(2) the runtime dynamically specifies that the size can be used without operator new and Delete.

(3) when the array is used as a function parameter, the array variable itself and its size are not passed separately because the size of the object has been Saved.

You should be aware of the overloaded subscript operator function:

(1) the function can only take one parameter, not multiple Parameters.

(2) do not overload as a friend function, it must be a member function of a non-static class. 2). overload increment 1 minus 1 Operator.

The increment 1 minus 1 operator is the Monocular Operator. They also have both prefix and suffix operations. To differentiate between these two operations, the suffix operation is treated as a unary operator. An expression

obj++ or obj--

is considered as:

Obj++0 or obj--0

Here is an example of an application that overloads the 1 minus 1 Operator.

#include

Class counter

{

Public

Counter () {v=0;}

Counter operator + + ();

Counter operator + + (int);

void Print () {cout<

Private

unsigned v;

};

Counter Counter::operator + + ()

{

v++;

Return *this;

}

Counter Counter::operator + + (int)

{

Counter t;

T.V = v++;

Return t;

}

void Main ()

{

Counter c;

For (int i=0; i<8; I++)

C + +;

C.print ();

For (i=0; i<8; I++)

++c;

C.print ();

}

3). overloaded function call operator

The function call operator () can be considered an extension of the subscript operation []. The function call operator can take 0 to more Arguments. The following example is used to familiarize itself with the overloads of the function call Operator.

#include

Class F

{

Public

Double operator () (double x, double y) const;

};

Double f::operator () (double x, double Y) const

{

return (x+5) *y;

}

void Main ()

{

F f;

Cout<

}

Definition and Summary of C + + main 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.