Analysis of the actual operation method of the C ++ Operator Overloading

Source: Internet
Author: User

C ++ programming language has become an important application language in the development field. There are a lot of advanced content that deserves continuous exploration in practice. Here, we will first understand the application method of the C ++ operator overload to further interpret this programming language.

  • What is the difference between the C ++ pointer and the reference?
  • How to Implement C ++ file stream operations
  • Sample Code for C ++ enum Enumeration
  • Discussion on the Application of C ++ Dynamic Array
  • Examples of various C ++ inheritance Methods

I. Why is the C ++ operator used for heavy loading?

For all operators of the system, generally, only the basic data types and classes provided in the standard library are supported. for user-defined classes, if you want to support basic operations, such as comparing the size, to determine whether the operators are equal, and so on, you need to define the specific implementation of this operator by yourself. For example, to determine whether two people are equally large, the default rule is to compare them by age. Therefore, when designing the class "person", we need to consider the operator =, and, according to the analysis just now, the comparison is based on age. So why is it heavy load? This is because the implementation version of the basic data type of this operator has been provided for us during the implementation of the compiler, but now its operand has become a user-defined data type class, so, you must provide the implementation of this parameter version by yourself.

2. How to declare a C ++ operator overload?

A: Operator Overloading is implemented as A class member function.

An overloaded operator is declared in the class body. The declaration method is the same as a common member function, except that its name contains the keyword operator and a c ++ predefined operator followed by it. You can declare a predefined = operator in the following way:

  1. class person{  
  2. private:  
  3. int age;  
  4.  public:  
  5.  person(int a){  
  6. this->aage=a;  
  7. }  
  8. inline bool operator ==(const person &ps) const;  
  9. }; 

The method for implementing the C ++ operator overload is as follows:

  1. inline bool person::operator==(const person &ps) const  
  2. { if (this->age==ps.age)  
  3.  return true;  
  4. return false;  

The call method is as follows:

  1.  #include  
  2. using namespace std;  
  3. int main()  
  4. { person p1(10);  
  5. person p2(20);  
  6. if(p1==p2) cout<<”the age is equal!”<return 0;   

Here, because operator = is a member function of class person, objects p1 and p2 can call this function. In the above if statement, it is equivalent to p1 calling function =, p2 is passed to the function as a parameter of the function to achieve comparison between two objects.

Consider the following if statement:

  1. if(10==p1) cout<<”the age is equal!”< 

Is the execution performed correctly?

The answer is no, because it is considered as a class member overload operator only when the left operand is an object of the class type. Because 10 is not a person object, you cannot call the classperson operator =.
Consider the following if statement:

  1. if(person(10)==person(11))  
  2.  cout<<"ok"< 

Can it be correctly executed? The answer is yes, because the operator is an anonymous object on both sides. The overloaded operators do not require the two operands to be of the same type. For example, we can define a subscript operator for class person to indicate the correspondence between the person and the phone number:

  1. /* Implement the subscript operator */
  2. # Include
  3. # Include
  4. Using namespace std;
  5. Class person
  6. {Private:
  7. Int tel;
  8. Public:
  9. Int & operator [] (string const & nm)
  10. {
  11. Return tel;
  12. }
  13. Int GetTel ()
  14. {
  15. Return tel;
  16. }
  17. };
  18. Int main ()
  19. {
  20. Person p1;
  21. P1 [& quot; suo & quot;] = 110;
  22. Person p2;
  23. P2 [& quot; rose & quot;] = 120;
  24. Cout <return 0;
  25. }

For operators that reload as member functions, the implicit this pointer is used as the first parameter of the function to represent the left operand.

B: the overload of the C ++ operator is implemented as a non-class member function (global function)

For global overload operators, parameters representing the left operand must be explicitly specified. For example:

  1. #include  
  2. #include  
  3. using namespace std;  
  4. class person  
  5. {  
  6. public:  
  7.  int age;  
  8. public:  
  9. }; 

The private data of this class cannot be accessed outside the class. Therefore, you must set the age to public.

  1. Bool operator = (person const & p1, person const & p2)
  2. {
  3. If (p1.age = p2.age)
  4. Return true;
  5. Return false;
  6. }
  7. Int main ()
  8. {
  9. Person rose;
  10. Person jack;
  11. Rose. age = 18;
  12. Jack. age = 23;
  13. If (rose = jack)/* two objects represent the Left and Right operands respectively */
  14. Cout <"OK" <return 0;
  15. }

C: How can I decide whether to reload an operator as a class member function or a global namespace member?

① If an overload operator is a class member, the operator will be called only when the left operand used with it is the object of this class. If the left operand of the operator must be of another type, the operator must be reloaded as a member of the global namespace.

② C ++ requires a value =, subscript [], call (), and the member pointing-> operator must be defined as a class member operator. Any definition that defines these operators as namespace members will be marked as a compilation error.

③ If an operand is a class type such as a string class, it is best to define a symmetric operator such as an equal operator as a global namespace member.

D: The operator overload is the method of the friend function.

If you reload the C ++ operator as a friend function, you can directly access the private data member of the authorization class within the function, this is the main difference between the method of user functions and the global namespace method.

E: How can I determine whether a non-class member operator should be a friend of the class or use a member to access the function? In general, the implementer of the class should try to minimize the number of operators represented inside the namespace function and the operator class. If you have provided access to member functions and they have the same efficiency, it is best to use these member functions. However, if the implementer of A Class decides not to provide access member functions for some private members of the class and the namespace operator must reference these private members to complete their operations, they must use the membership mechanism. For example:

  1. #include  
  2. #include  
  3. using namespace std;  
  4. class person{  
  5. public:   
  6.  int age;  
  7. public:  
  8. };   
  9. bool operator==(person const &p1 ,person const & p2)  
  10. {  
  11. if(p1.age==p2.age) return true;  
  12. return false;  
  13. }  
  14. ostream operator<<(ostream &os,person const &p)  
  15. {  
  16. os<<"the person age is:"<return os;  
  17. }  
  18. int main()  
  19. {  
  20. person rose;  
  21. person jack;  
  22. rose.age=18;  
  23. jack.age=23;  
  24. cout</*call ostream operator<<(ostream &os,person const &p) */  
  25. cout<return 0;  

Iii. Design of C ++ Operator Overloading

Class 1 designers cannot declare a non-predefined overload operator.

② Other operators cannot be defined for built-in data types.

③ The predefined operator priority cannot be changed.

④ Which operators should be provided for a class are determined by the intended use of the class.

4. prefix and postfix

To distinguish post-operator and pre-operator declarations, the declaration of the auto-increment and post-decimal operators for overload has an additional int type parameter. No parameter name is required because it is not used in operator definition. The extra integer parameter is transparent to users of the post operator, and the compiler provides it with the default value, so this parameter can also be ignored. For example:

  1. #include  
  2. #include  
  3. using namespace std;  
  4. class person  
  5. {  
  6. private:  
  7.  int age;  
  8. public:  
  9.  person(int a)  
  10.  {  
  11.  aage=a;  
  12.  }  
  13. person const operator++()/*prefix ++ */  
  14. {  
  15.  this->age++;  
  16.  return *this;  
  17. }  
  18. person const operator++(int a)/*postfix ++ */  
  19. {  
  20.  person temp(1);  
  21.  temp=*this;  
  22.  this->age++;  
  23.  return temp;  
  24. }  
  25. int GetAge()  
  26. {  
  27.  return age;  
  28. }  
  29. };  
  30. int main()  
  31. {  
  32. person rose(10);  
  33. person jack(20);  
  34. person marry(22);  
  35. person tom(30);  
  36. jack=++rose;  
  37. marry= tom++;  
  38. return 0;  

The preceding section describes how to overload the C ++ operator.

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