C + + NOTE-operator overloading

Source: Internet
Author: User
Tags arithmetic operators

Operator overloading is a frequently used knowledge point in C + + and an important support point for C + + extensibility.

Today I'm going to apply the operator overloading in all cases, for example, and then we'll know the power of operator overloading and the convenience it brings.


There are two forms of operator overloading functions:

1. As a member function of a class

Assignment (=), subscript ([]), Call (()), member Access Arrow (-), these four operators must be member functions, and other operators can be either member functions or non-member functions.

Note: If we define an operator function as a member function, its left operand must be an object of the owning class.

2, as a non-member function

In general, only symmetric operators are defined as non-member functions (such as: &&, = =), non-member functions, and, generally, the friend function of the class.


It can be seen that if an operator is defined as a non-member function, the number of formal parameters is one more than it is defined as a member function.


The following are the overloads of the various operators


1. Overloaded input and output operators

<span style= "FONT-SIZE:12PX;" >class base{public:    base () {}    base (int new_x, double new_y):        x (new_x), Y (new_y)   {}    Friend IStream &operator>> (IStream &in, base &chs);    Friend Ostream &operator<< (ostream &out, base &chs);p rivate:    int x;    Double y;}; IStream &operator>> (IStream &in, base &chs) {    in>>chs.x>>chs.y;    return in;} Ostream &operator<< (ostream &out, base &chs) {    out<<chs.x<< "  " <<chs.y ;    return out;} </span>


such as the code:

1, the input and output must be defined as a friend function, because if we are defined as a member function, then it means that the first argument must be the object of the class, then we call this time:

<span style= "FONT-SIZE:14PX;" >    base x;    X>>cin;</span>

2, we generally have to return a reference to the stream, because this is to allow continuous input: cin>>x>>y;


2. Arithmetic and relational operators

Arithmetic operators are mostly ordinary operators, such as: +-*/&& | | ! Equal operators

where arithmetic operators and relational operators are generally non-member functions.

The following explains why arithmetic operators and relational operators cannot be member functions:

1. If the operator ' + ' is a member function

Class Base{public:    base () {}    base (int new_x, double new_y):        x (new_x), Y (new_y)   {}    <span style= "Color: #ff0000;" >base operator + (const base &chs)    {        x + = chs.x;        Y + = Chs.y;        return *this;    } </span>private:    int x;    Double y;};
Base x (1, 2.1), Y (3, 3.4), Z;
z = x+y;                This time that changed x, also changed z, but our intention is only to change in, and not change x;

2. The following is a friend function

Base operator + (const base &CH, const base &chs) {    base BZ = ch;    bz.x + = chs.x;    Bz.y + = Chs.y;    return BZ;}

<pre class= "cpp" name= "code" >base x (1, 2.1), Y (3, 3.4), Z;
z = x+y;   At this point, we are using an intermediate variable in the function, so only z is changed, and X is unchanged.

By the above we know that the function form of an operator overload is critical, and if you use the wrong function form, you may be in danger of unexpected risk.

So, when we're going to write a function overloaded with operators, let's start by figuring out what this operator is doing, what we can do with built-in types, and whether we're going to use them as member functions or non-member functions.


3. Subscript operator [i]

Subscript operators are used primarily for arrays, pointers, containers, and so on, and the subscript operators have the following points:

1, the value of the position in the array is obtained by the subscript operator.

2, we also need to change the value of the position by the subscript operator

As we can see, the subscript operator must be a member function.

Eradicate the above function analysis, we can get

1, the function needs an shaping parameter, tells the function to go to which position the value

2. function must return the reference value of the position

3, we need to overload a constant version of the function.

From above, we get the code:

Char &base::operator [] (int i) {    if (i >= length)  return chs[0];    return chs[i];} const char &base::operator [] (int i) const{    if (i >= length)  return chs[0];    return chs[i];}


4. Increment decrement operator

We often use (--) and (+ +) operators on iterators or on built-in types, and for starters, they definitely want to kill the two operators. Below we will use the (+ +) operator to analyze its effect;

For the increment (+ +) operator

1. The operator increments the value of the variable directly before the variable

2, the operator is behind the variable, then we need to save the state of the object, and then the increment of the value of the pass to him

For these two operators, we generally write functions as member functions.

We first write the function preceded by the increment operator, and we return the reference to the variable itself.

Base &base::operator + + () {    x + = 1;    return *this;}

Increment operator (+ +) back, at which point we need to consider how we can implement it, save its state first?

So, we're going to go back to an intermediate variable, and the next time we call that variable, it's the incremented variable.

Since we are returning an intermediate variable, we cannot return a reference.

<span style= "color: #000000;" >base base::operator ++<span style= "color: #cc0000;" > (int) </span>{    base BZ = *this;    x + = 1;    return BZ;} </span><span style= "color: #990000;" ></span>

A shape parameter is added because the compiler needs to differentiate between pre-and post-conditions. So next time we call, we'll have to pass a shape to it.


5. Function call operator ()

The function call operator must be a member function.

The function call operator, which allows us to invoke the object of the class like a function call

Class Base{public:    void Operator () ()    //Function call operator    {        cout<<x<<endl;    }    with no arguments void operator () (int z)     //There is an reshape parameter    {        cout<<x+z<<endl;    } Private:    int x;};
Here is the invocation form
Base x;
X ();            Call the first function
X (4);              //Call a second function

A lambda table in C + + is similar to overloading a function call operator function in a class.


6. Type conversion operator, int double

The type conversion operator is responsible for converting a class to another required type

Therefore, it does not show the return type, nor does it have any parameters.

Class Base{public:    operator int ()    {        return x;              Turn the class type to Huang a shaping    }private:    int x;};
This is a conversion that can be either invisible or can be displayed.
Base x;
int z = x, y = static_cast<int> (x);
If you precede the function with explicit, you can only display conversions

explicit operator int ();
int x = z;    This is wrong and cannot be implicitly converted
int x = static_cast<int> (x);


When we overload the type conversion operator, we must be careful with two semantics.


Operator overloading does bring us a lot of freedom and convenience. But at the same time it also poses a danger, so we must pay attention to the home when using.

When we overload operators, we have to remember that overloaded operators must conform to the nature of the operator itself, as well as to the use of this operator on our built-in types.



Share.













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.