Summary of C + + review essentials seven-operator overloading

Source: Internet
Author: User
Operator overloading
The so-called overloading, is to re-give new meaning. A function overload is a function that assigns a new meaning to an existing function, enabling it to implement new functionality, so that a function name can be used to represent functions of different functions, which is "one more use".

Operator can also be overloaded. In fact, we have unconsciously used operator overloading. For example, everyone has become accustomed to adding operators "+" to the integer, single-precision and double-precision number of addition operations, such as 5+8, 5.8 +3.67, and so on, in fact, the computer for integer, single-precision number and double-precision number of the addition operation process is very different, but because C + + has been overloaded operator "+", So it can be applied to an int, float, double type operation.

The operand of a predefined operator in C + + can only be a basic data type. In practice, however, similar operations are required for many user-defined types, such as classes. These operators must be redefined in C + +, giving the existing operators new functionality that enables them to perform specific operations on specific types. The essence of operator overloading is function overloading, which provides the extensibility of C + + and is one of the most attractive features of C + +.

Operator overloading is implemented by creating operator functions, which define the operations that the overloaded operators will take. The definition of an operator function is similar to that of other functions, except that the function name of the operator function is made up of the keyword operator and the operator symbol to be overloaded later. The general format of the operator function definition is as follows:

< return type descriptor > operator < operator symbol > (< parameter table >)





{     < function body;}


The following rules apply to operator overloading:



(1) Except for the generic relational operator ".", the member pointer operator ". *", The scope operator "::", the sizeof operator and the three-mesh operator "?:", all operators in C + + can be overloaded.

(2) Overloaded operators restrict the allowed overloaded operators in the range of operators that are already in the C + + language, and cannot create new operators.

(3) Operator overloading is essentially a function overload, so the compiler's choice of operator overloading follows the selection principle of function overloading.

(4) An overloaded operator cannot change the precedence and binding of an operator, nor can it change the number of operator operands and the syntax structure.

(5) Operator overloading cannot change the meaning of the operator for an intrinsic type object. It can only be used with objects of user-defined types, or when mixed with objects of the user-defined type and internal types.

(6) Operator overloading is the proper modification of the original operator for the actual need for the new type of data, and the overloaded functionality should be similar to the original functionality, avoiding the use of overloaded operators without destination.



operator function overloading generally has two forms: overloading the member functions of the class and overloading the non-member functions of the class. A non-member function is usually a friend. (an operator can be overloaded as a non-member, non-friend function.) However, when such an operator function accesses private and protected members of a class, you must use the set data and functions that are available in the public interface of the class to read the data, which can degrade performance when called. These functions can be inline to improve performance. )



member function operators



The general format of operator overloading for member functions of a class is:



<function type> operator <operator> (<parameter table>)

   {

    <function body>

   }


When an operator is overloaded with a member function of a class, the number of arguments to the function is one less than the original operand (except for the post-order operator), because the member function implicitly accesses an object of the class with the this pointer, which acts as the leftmost operand of the operator function. So:



(1) When the binocular operator is overloaded as a member function of a class, the function explicitly describes only one parameter, which is the right operand of the operator.

(2) When the pre-order operator is overloaded as a member function of a class, there is no need to explicitly describe the parameter, that is, the function has no formal parameters.

(3) When the post-order operator is overloaded with a member function of a class, the function takes an integer parameter.

The calling member function operator is in the following format:



    < object name >.operator < operator > (< parameters >)


It is equivalent to



    < object names >< operators >< parameters >


For example: A+b is equivalent to A.operator + (b). In general, we use the idiomatic expressions of operators.



Friend function operators



The general format of the friend function for an operator overload for a class is:



Friend <function type> operator <operator> (<parameter table>)
{
  <function body>
}


When an operator is overloaded with a friend function of a class, because there is no implied this pointer, the number of operands does not change, and all operands must be passed through the function's formal parameters, and the arguments of the function correspond to the operands from left to right.



The format of the function operator is as follows:



  Operator < operator > (< parameter 1>,< parameter 2>)


It is equivalent to



    < parameter 1>< operator >< parameter 2>


For example, A+b is equivalent to operator + (A, b).



Comparison of two types of overloaded forms



In most cases, overloading the operator with the member function of the class and the friend function of the class is possible. But the member function operator and the friend function operator also have their own characteristics:



(1) In general, the monocular operator is best to overload the member function of the class; The binocular operator is best to overload the friend function of the class.

(2) Some of the following binocular operators cannot be overloaded with the friend function of a class: =, (), [], and.

(3) A type conversion function can only be defined as a member function of a class and cannot be defined as a friend function of a class.

(4) If the operation of an operator needs to modify the state of an object, it is preferable to select overload for the member function.

(5) If the operand required by the operator (especially the first operand) wishes to have an implicit type conversion, only the friend function is selected.

(6) When an operator function is a member function, the leftmost operand (or only the leftmost operand) must be a class object of the operator class (or a reference to the class object). If the operand on the left must be a non-homogeneous object, or an object of an intrinsic type, the operator function must be implemented as a friend function.

(7) When an overloaded operator is required to be exchangeable, select overload as a friend function.



1 Why the operator overloading mechanism is used (recall function overloading)



Using the plural class example//complex C3 =c1 + c2;



Cause complex is a user-defined type, and the compiler doesn't know how to add or subtract



The compiler provides a mechanism for users to do their own work, adding and subtraction of custom types .....



This mechanism is the operator overloading mechanism



The essence of the 2 operator overload is a function















For example 1:



/ / Through the class member function - operator overload (function definition in the class)

/ / Function declaration Complex operator- (Complex & c2)

/ / Use class member function to achieve - operator overloading

Complex c4 = c1 - c2;

c4.printCom(); //printout

//c1.operator-(c2);


For example 2:



/ / Complete the + operator overload through the global function method (the function is defined outside the class)

//Function declaration Complex operator+(Complex &c1, Complex &c2)

/ / Function call analysis

Int main()

{ Complex c1(1, 2), c2(3, 4);//Define two objects

//Complex c31 = operator+(c1,c2); The calling mode of the function

Complex c3 = c1 + c2; // shorthand +

c3.printCom();

}


Feel the operation process:

For example 3:

/ / Pre-++ operator with global function implementation

Complex& operator++(Complex&c1)

{ c1.a ++;

C1.b ++;

Return c1;

}

/ / call method

++c1 ; //=è need to write out the operator overloaded function prototype

c1.printCom();

// operator overloaded function name definition

/ / First recognize that the operator overload is a function to define the function name --->operator++

/ / Analysis function parameters according to the number of left and right operands ------->operator++(Complex &c1)

/ / Analysis function return value -------> Complex&operator++ (Complex &c1) returns itself


For example 4

//4.1 pre-operator member function implementation

Complex& operator--()

{ this->a--;

This->b--;

Return *this; //note return

}

//4.2 calling method

--c1;

c1.printCom();

//4.3 preamble - operator overloaded function name definition

//c1.operator--()


For example 5:



//5.1//post ++ operators are implemented with global functions

Complex operator++(Complex &c1, int)

{ Complex tmp = c1;

C1.a++;

C1.b++;

Return tmp;

}

//5.2 calling method

C1 ++ ; //Use ++ first

//5.3 Post ++ operator overloaded function name definition

Complex operator++(Complex&c1, int) //The difference between function placeholder parameter and pre-++


For example 6:



//6.1 Post-operator with class member function

Complexoperator--(int)

{ Complextmp = *this;

This->a--;

This->b--;

Return tmp;

}

//6.2 calling method

C1 ++ ; //Use ++ first

//6.3 Post--operator overloaded function name definition

Complex operator--(int) // function placeholder parameter and pre-position - difference


Summary of pre-and post-operators

Using a placeholder parameter in C + + to differentiate between pre-and post-operations



To define operator overloaded function names



Global functions, class member function methods implement operator overloading steps

1) to admit that operator overloading is a function, write out the function name operator+ ()

2) write the function parameters according to the operand

3) According to the business, perfect function return value (see function is return reference or pointer element), and implement function business



Application scenarios for operator overloading with friend function



1) friend function and member function selection method

Ø When the class of the left operand cannot be modified, use the global function to reload

Ø =, [], () and -> operators can only be overloaded by member functions

2) Reload with friend function << << operator

Ø istream and ostream are C++ predefined stream classes

Ø cin is an object of istream, cout is an object of ostream

Ø Operator << Overloaded by ostream as an insert operation for outputting basic type data

Ø Operator >> Reloaded by istream as extraction operation for inputting basic type data

Ø Reload << and >> with friend function to output and input user-defined data types

a) Implement the << operator with a global function method

Ostream& operator<<(ostream &out, Complex &c1)

{ //out<<"12345, life is really bitter"<<endl;

Out<<c1.a<<"+ "<<c1.b<<"i "<<endl;

Return out;

}

/ / call method

Cout<<c1;

//chain programming support

Cout<<c1<<"abcc";

//cout.operator<<(c1).operator<<("abcd");

/ / Function return value as an lvalue needs to return a reference

b) class member function methods cannot be implemented << operator overloading

/ / Because of the source code of cout this class

//cout.operator<<(c1);

3) friend function overload operator use note point

a) The friend function overloading operator is often used when the left and right operand types of the operator are different.

b) other

Ø In the case where the first parameter requires implicit conversion, using the friend function overload operator is the correct choice.

Ø Friends function does not have this pointer, the required operand must be explicitly declared in the parameter table, it is easy to implement implicit conversion of the type

Ø C++ can not be overloaded with the operator function operator

= () [] -> 


Excuse me: why the arithmetic overloaded member function has only one parameter, and the friend function has two?

Since the member function has this pointer to the object, arguments can be passed through the object, and the friend function has no this pointer, so there must be two arguments. (for two-element operator overloading)



The above is the C + + review points summary of the seven-operator overloaded content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • 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.