C + + Primer learning note _26_ operator overloading and conversion (1)--overload/non-overloaded operator, member function mode overload, Friend function mode overload

Source: Internet
Author: User
Tags function prototype

C + + Primer learning note _26_ operator overloading and conversion (1)--overload/non-overloaded operator, member function mode overload, Friend function mode overload

Introduction:

Use operator overloading wisely to make the use of class types as intuitive as built-in types!


first , overloaded operator name

Like any other function, the operator overload function has a return value and a formal parameter list. The formal parameter list must have a formal parameter with the same number of operators. such as the assignment of binary operations, so the operator function has two parameters: the first parameter corresponds to the left operand, the second parameter corresponds to the right operand.

Most operators can be defined as member functions or non-member functions. When the operator is a member function, its first operand is implicitly bound to the this pointer. Some operators, such as assignment operators, must be member functions of the class. For example, the assignment of this is bound to a pointer to the left-hand operand. Therefore, the assignment operator accepts a single parameter, and the parameter is an object of the same class type. The right operand is generally passed as a const reference.

Not all operators can be overloaded, as in the following table:

Operators that can be overloaded

+

-

*

/

%

^

&

|

~

!

,

=

<

>

<=

> =

+ +

--

<<

>>

= =

! =

&&

| |

+=

-=

/=

%=

^=

&=

|=

*=

<<=

> >=

[]

() /span>

-

->*

New

New[]

Delete

Delete[]


operators that cannot be overloaded

::

.*

.

?:



1, the main bearing in mind the operator cannot be overloaded: (Can strengthen memory like this: with " Point "is not overloaded )

Scope resolution operators::

Conditional operator? :

The direct member access operator.

The operator that the class member pointer refers to. *

sizeof operator sizeof

Note: the. * is a C + + class member function pointer call operator that is used to invoke a class function pointer.
Example:
Suppose you have a ClassA class that has a member function, void classa::func (int i), you can use this:

ClassA obj;  FP = &ClassA::func; Assign a value to this class function pointer  

2. Operator overloading does not allow the creation of new operators.


3. Overloaded operators must have a class type operand

An operator for a built-in type whose meaning cannot be changed:

int operator+ (int,int); Error

overloaded operators must have operands of at least one class type or enumeration type . This rule forces overloaded operators to not redefine the meaning of operators for built-in type objects.

4. Priority and binding are fixed

The precedence, associativity, or number of operands of an operator cannot be changed.


"Best Practices"

overloaded commas, fetch addresses, logical and, logical, or equal operators are usually not good practices ! These operators all have built-in meanings, and if we define our own versions, we can no longer use these built-in meanings!



Second, member function overloading

The format of the member function prototype:


The format of the member function definition:

function type class name:: operator operator (parameter table)  {       function body;  }  



Third, non-member function overloading

The format of the friend function prototype:

Friend function type operator operator (parameter table);  


The format of the friend function definition:

function type class name:: operator operator (parameter table)  {      function body;  }  


"One instance: overloaded operator +"

#include <iostream> using namespace std;      Class Complex {public:complex (int real, int imag);      Complex (void);       ~complex (void);      Complex &add (const Complex &other);      void Display () const;    Complex operator+ (const Complex &other);  Friend Complex operator+ (const Complex &AMP;C1, const Complex &AMP;C2);      Private:int Real_;  int imag_;  }; Complex::complex (int real, int imag): Imag_ (Imag), Real_ (real) {} complex::complex (void) {} complex::~complex (void) {      } Complex &complex::add (const Complex &other) {Real_ + = Other.real_;      Imag_ + = Other.imag_;  return *this;  } void Complex::D isplay () const {cout << real_ << "+" << imag_ << "i" << Endl;      } Complex complex::operator+ (const Complex &other) {int r = Real_ + Other.real_;      int i = Imag_ + other.imag_;  Return Complex (R, I); } Complex operator+ (const Complex &AMP;C1, const Complex &AMP;C2)//And previous functionEquivalence, comment on the previous function, the same as the effect of implementing the current function {//int r = C1.real_ + C2.real_;  int i = C1.imag_ + c2.imag_;  Return Complex (R, I);      } int main (void) {Complex C1 (3, 5);      Complex C2 (4, 6); C1.      ADD (C2); C1.      Display (); Complex C3 = C1 + C2; Equivalent to c1.opertor+ (C2);      or operator+ (c1, C2); C3.      Display ();  return 0;   }
Operation Result:

7+11i
11+17i

Explanation: The Add member function was implemented, but C1. ADD (C2); The change is C1 itself; if we want to implement the plus-sign expression, C3 = C1 + C2; You can implement the operator+ operator overload, either as a member function or as a friend, and if the two coexist, the member function takes precedence.



Iv. some basic concepts

(1) Example 1: The following operators, which cannot be overloaded in the C + + language are ()

A, * B,? : C,:: D, delete

Solution: BC.


(2) Example 2: What is the difference between a copy constructor and an assignment operator?

Answer: The first thing to note is that if the user does not have a definition, C + + implicitly declares a copy constructor and an assignment operator. The two are very similar, but there is a big difference in the following: the copy constructor is called only when the object is instantiated, that is, during the copy constructor call , the object is in a pending state (until the copy constructor is successfully called) , the copy constructor does not return any values, and void does not. The assignment operator is called when an existing object is assigned a new value, and it has a return value.

The "=" does not appear to call the assignment constructor:

String Book1 ("9-999-9"), BOOK3;  string book2 = Book1;    Call the copy constructor to produce a new object Book2  book3 = Book1;    Call assignment operator, no new object generated  

So it is possible to see whether a new object has been created to determine whether the copy constructor was called or the assignment operator was called.

For more information about the copy constructor, refer to: Blog: Class and Data Abstraction (5) _ Initialize list (const and reference member), copy constructor


(3) Example 3: Which of the following functions can be inherited?

A, constructor B, destructor C, copy constructor D, assignment operator overload function

E, above can be F, above can not

Answer: F. The constructors of the base class (including copy constructors), destructors, and assignment operator overloading functions cannot be inherited by derived classes.


(4) What member functions are generated by default for empty classes in 4:c++?

Answer: The empty class defaults to the resulting constructor, copy constructor, destructor, assignment operator overload function, accessor operator overload function, const accessor operator overload function, and so on. As follows:

Class empty  {public  :          empty ();//default constructor          empty (const empty&);  Copy constructor          ~empty ();  destructor          empty& operator= (const empty&);  The assignment operator          empty* operator& ();  The accessor operator is          const empty* operator& (() const;  Accessor operator Const  };  



Reference:

C + + Primer Fourth Edition


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + Primer learning note _26_ operator overloading and conversion (1)--overload/non-overloaded operator, member function mode overload, Friend function mode overload

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.