Introduction to C + + overloaded operations

Source: Internet
Author: User
Tags arithmetic operators

This article is based on the "C + + Primer (5th edition)" in 14 chapters and "more effective C + +" clause 7, organized.

In fact, before writing this blog, the heart is still very disturbed, because, Bo Master's level is very limited, the field of vision is narrow, if in the process of understanding the book has a deviation, to read this blog to the wrong understanding of the people, that sin is big. Again, this article is only a brief introduction, if there are errors in the place welcome message points out.

Personally, the most important thing for operators is to use the same meaning as built-in types.

First, the basic concept

    • When an operation acts on an operand of a class type, the meaning of the operator can be redefined by operator overloading.

Overloaded operators are functions with special names, whose names are composed of the keyword operator and the operation symbols to be defined later. It includes: return type, argument list, and function body.

Overloaded operator functions have as many arguments as the operators do, such as: Unary operators have one parameter and two-tuple operators have two. It is worth noting that when the operator function is a member function, its first (left) operand is bound to the implicit this pointer, so the number of member operator functions (Explicit) parameters is one less than the total number of operands of the operator, but the total number is the same.

1. Some operators should not be overloaded

Operators that cannot be overloaded are:

. .* :: ?:
New Delete sizeof typeID
Static_cast dynamic_cast Const_cast Reinterpret_cast

Operators that can be overloaded but are best not overloaded are:

(1) logic and &&, Logic or | |

Both the logical and the operator and the logical OR operator are the values of the left operand and the right operand, and the value of the right operand is computed only if the left operand cannot determine the result of the expression, which is known as the short-circuit evaluation (short-circuit evaluation).

"More effective C + +" gives an example, if overloading operator &&, the following is the equation:

1 if (expression1 && expression2) ...

will be considered by the compiler as one of the following:

1 // Suppose operator&& is a member function 2 if (expression1. operator&&(expression2)) ... 3 4 // Suppose operator&& is a global function 5 if (operator&& (expression1,expression2)) ...

That is, the short-circuit evaluation property of built-in operators cannot be preserved, and two operand objects are always evaluated.

(2) Comma,

The Order of evaluation for the comma operator is evaluated from left to right, and the real result of the comma operator is the value of the right-hand expression. If you intend to overload the comma operator, you must imitate such behavior, but you cannot perform these necessary imitations. The Order of evaluation and the return result are satisfied at the same time.

2. Select member functions or non-member functions

When we define an overloaded operator, you must first decide whether to declare it as a member function of a class or as a normal non-member function. (For member functions and non-member functions, see the choice of member functions and non-member functions). Here are some guidelines to help us choose:

(1) Assignment (=), subscript ([]), Call (()), and member Access Arrow (-) operator must be a member;

(2) Compound assignment operators should generally be members, but not necessarily;

(3) An operator that alters the state of an object, or an operator that is closely related to a given type, such as an increment, decrement, and dereference operator, usually a member;

(4) An operator with symmetry may convert an arbitrary segment of an Operator object, such as arithmetic, equality, relational, and bitwise operations, so they should usually be ordinary non-member functions.

Second, various heavy-duty

1. Overloaded output operators << and input operators >>

(1) Overloaded output operators <<

Typically, the first parameter of the output operator is a reference to a very ostream object, and the reason Ostream is very much because writing to the stream alters its state, and the parameter is a reference because we cannot directly copy a Ostream object The second parameter is typically a reference to a constant, and is a reference because you want to avoid copying arguments, and the reason that the parameter can be a constant is because (usually) the printed object does not alter the object's contents. In addition, to be consistent with other output operators, the Ostream parameter is returned.

1 ostream &operator<< (ostream &os,const Sales_data &Item)  2{3     os<<item.isbn () <<""<<item.avg_price (); 4     return os; 5 }

(2) overloaded input operator >>

Typically, the first parameter of the input operator is a reference to the stream that the operator will read, and the second parameter is a reference to the (very) object that will be read in. The operator typically returns a reference to a given stream. The second parameter must be a very good amount, because the purpose of the input operator itself is to read the data into the object.

1IStream &operator>> (IStream & is, Sales_data &Item)2 {3     DoublePrice ;4      is>>item.bookNo>>item.units_sold>>Price ;5     if( is)//you must handle situations that may fail6     {7item.revenue=item.units_sold*Price ;8     }9     Else        //If it fails, the object is given the default stateTen     { Oneitem=Sales_data (); A     } -     return  is; -}

The following error may occur when you enter:

The read operation may fail when the stream contains data of the wrong type, and the read operation will fail if it reaches the end of the file or encounters other errors in the input stream.

The input operator should be responsible for recovering from the error.

(3) Input and output operators must be non-member functions

If members of the class, their left operand will be an object of our class:

1 sales_data data; 2 data<<cout;     // If operator<< is a member of Sales_data

If the input and output operators are members of a class, they must also be members of IStream or ostream, however, this class belongs to the standard library and we cannot add any members to the classes in the standard library.

2. Arithmetic and relational operators

In general, arithmetic and relational operators are defined as non-member functions to allow conversion of operands on the left or right, because these operators generally do not need to alter the state of the operands, so the parameters are references to constants.

(1) Arithmetic operators

The arithmetic operator usually computes its two operands and obtains a new value, which differs from any operand, often within a local variable, and returns a copy of the local variable as its result after the operation is completed.

1 operator+ (const sales_data &lhs,const Sales_data &RHS)2{  3     sales_data sum=lhs; 4     sum+=RHS; 5     return sum; 6 }

(2) Equality operator

A class in C + + checks that two objects are equal by defining an equality operator, and compares each data member of an object, and considers the two objects equal only if all corresponding members are equal.

1 BOOL operator==(ConstSales_data &AMP;LHS,ConstSales_data &RHS)2 {3     returnLHS.ISBN () ==RHS.ISBN () &&4lhs.units_sold==rhs.units_sold&&5lhs.revenue==rhs.revenue;6 }7 8 BOOL operator!=(ConstSales_data &AMP;LHS,ConstSales_data &RHS)9 {Ten     return! (lhs==RHS); One}

3. Assignment Operators

Assignment operators must be defined as member functions

(1) Copy Assignment

The Copy assignment operator accepts a parameter of the same type as the class in which it resides:

1 class Foo 2 {3public:4     Foo &operator= (const foo&);     // Assignment Operators 5     // ... 6 }

(2) Move assignment operator

The move assignment operator does not throw any exceptions, mark it as NOEXECPT, like the copy assignment operator, and the move assignment operator must handle the self-assignment correctly:

1Strvec &strvec::operator= (Strvec &&RHS) NOEXECPT2 {3     if( This!=&AMP;RHS)//Direct detection of self-assigned values4     {5          Free();//releasing an existing element6elements=rhs.elements;//taking over resources from RHS7First_free=Rhs.first_free;8cap=Rhs.cap;9Rhs.elements=rhs.first_free=rhs.cap=nullptr;//Place RHS in a destructor stateTen     } One     return* This; A}

(3) The third assignment operator defined by the standard library vector class, which takes a list of elements within curly braces as arguments, such as:

1 vector<string> v; 2 v={"a","an"};

Operator is added to the Strvec class:

1Strvec &strvec::operator= (initiallizer_list<string>IL)2 {3     //alloc_n_copy allocating memory space and copying elements from within a given range4Auto Data=alloc_n_copy (Il.begin (), Il.end ());5      Free();//destroys elements in an object and frees up memory space6Elements=data.first;//To update a data member to point to the new space7first_free=cap=Data.second;8     return* This;9}

4, increment and decrement operators

(1) Define a pre-increment, decrement operator

They first call the check function to verify that the strbolbptr is valid, and if so, then check if the given index value is valid, and if the check function does not throw an exception, the operator returns a reference to the object.

1 classstrblobptr2 {3  Public:4strblobptr&operator++();5strblobptr&operator--();6 }7 8strblobptr& strblobptr::operator++()9 {Ten     //if the Curr has already pointed to the end position of the container, it cannot be incremented OneCheck (Curr,"increment past end of Strblobptr"); A++Curr; -     return* This; - } the  -strblobptr& strblobptr::operator--() - { ---Curr; +Check (Curr,"decrement past begin of Strblobptr"); -     return* This; +}

(2) Define the post increment, decrement operator

and a pre-compare post-build accepts an additional parameter of type int (not used).

1 classstrblobptr2 {3  Public:4strblobptr&operator++(int);5strblobptr&operator--(int);6 }7 8strblobptr& strblobptr::operator++(int)9 {TenStrblobptr ret=* This;//Make a note of the current value One++* This;//requires pre + + Check to be valid A     return*ret;//returns the status of a previous record -}

In addition, the other operators see the book "C + + Primer (5th edition)".

Introduction to C + + overloaded operations

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.