[C++primer] [14] overloaded operators and conversions

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators class definition

14.1 Definition of overloaded operators

The operator cannot be overloaded:. ?: sizeof::. *

Additional new operators cannot be defined for any built-in type; precedence and binding are fixed; no short-circuit evaluation feature is recommended (no overloading &&, | |, comma);

The arithmetic and relational operators are generally defined as non-member functions, whereas assignment operators are defined as members;

How to use overloaded operators:

1) The same as the built-in type using operator mode;

2) You can also call an overloaded operator function like a normal function, specify a function and pass an appropriate number of formal parameters of the appropriate type;

Item1 + = item2; Expression based "call" item1.operator+= (ITEM2); Equivalent call to member operator function
Design of overloaded operator

1) do not overload operators with built-in meanings. If there are no specific overloaded versions, the compiler defines the following operators on its own :

-synthetic assignment operator (=): Assigning values on a per-member basis

-Fetch address operator (&), comma operator (,) consistent with built-in meanings

-Built-in logic with (&&) and logic or (| | Operator uses a short-circuit evaluation, which is redefined to lose the feature.

2) Most operators do not make sense for class objects, and when designing a class, you should determine which operators to support.

3) Compound assignment operator. If a class has an arithmetic operator or bitwise operator, it is generally a good practice to provide the corresponding compound assignment operator.

4) Equality and relationship operators. Classes that will be used as associative container types should define the < operator, and even if the class is stored only in the sequential container, the equality operator and the less-than operator should be defined, and if the class defines an equality operator, it should also define unequal operators.

5) Select Member or non-member implementation (experience principle)

- assignment of subscript calls and member access arrows (=, [], (), and so on) operators must be defined as members , and those operators defined as non-members will be marked as errors at compile time;

-compound assignment is usually defined as a member of a class (it is not necessary to do so);

-Some operators that change the state of an object or are closely related to a given type are usually defined as members, such as self-increment self-reduction references

-symmetric operators, such as arithmetic, equality, relations, and bitwise operators, are best defined as non-members.

14.2 overloading of input and output operator output operators <<
ostream&operator<< (ostream& out, const sales_item& s) {out << s.isbn << "\ t" << S.uni  Ts_sold << "\ t" << s.revenue << "\ T" << s.avg_price (); return out;} Note: The IO operator must be a non-member function
Overloading of input operators >>
Istream&operator>> (istream& in, sales_item& s) {double price;  In >> s.isbn >> s.units_sold >> Price;  Check the inputs succeeded if (in) s.revenue = S.units_sold * PRICE; else S = Sales_item (); Input Failed:reset object to the default state, return in;}
14.3 arithmetic operators and relational operators

Generally, the arithmetic and relational operators are defined as non-member functions

Arithmetic operators
Assumes that both objects refer to the same isbnsales_itemoperator+ (const sales_item& LHS, const sales_item& RH s) {sales_item ret (LHS);//copy LHS into a local object that we ll return ret + = RHS;//Add in the contents of RHS re Turn ret; return ret by value}

Note: Classes of arithmetic operators and associated compound assignment operators are defined at the same time, and arithmetic operations are generally implemented with compound assignments

Equality operators
Inline booloperator== (const sales_item &LHS, const Sales_item &RHS) {//must be made a friend of Sales_item Retu RN Lhs.units_sold = = Rhs.units_sold && lhs.revenue = = rhs.revenue && lhs.same_isbn (RHS);}
Inline booloperator!= (const sales_item &LHS, const Sales_item &RHS) {return! LHS = = RHS); ! = defined in terms of operator==}
14.4 Assignment Operators

The assignment operator must be a member of the class, and the assignment must return a reference to the *this

14.5 subscript operator

The subscript operator returns a reference. You typically define two versions: one is a non-const member and returns a reference, and one returns a const reference for a const member.

Class Foo {Public:int &operator[] (const size_t);  const INT &operator[] (const size_t) const;  Other interface membersprivate:vector<int> data; Other member data and private utility functions};
14.6 member access operator

The arrow (-) operator is generally a class member, and the dereference (*) does not require a member to be defined, but it is also correct as a member.

Class Screenptr {public://constructor and copy control, as before screen &operator* () {return *ptr->sp;  } screen *operator-> () {return ptr->sp;}  Const screen &operator* () const {return *ptr->sp;} Const screen *operator-> () const {return ptr->sp;} Private:scrptr *ptr; Points to use-counted Scrptr class};
Overloaded Solution Reference

Defines the const and non-const versions of the dereference operation, respectively, and the const member returns a const reference to prevent the user from altering the underlying object.

Overloaded arrow operator

Act like a two-dollar operator: accepts an object and a member name. The right-hand operand that references an object to get the member,-> corresponds to an identifier for the class member.

When written: Point->action ();

Because of the priority rule, it is equivalent to (point->action) ();

1) If point is a pointer to a class object with an action member, the compiler compiles the code to invoke the object's action member;

2) If point is a class that defines the operator-> operator, Point->action is the same as point.operator-> ()->action, and then uses that result to repeat the three steps.

3) Otherwise, the code is faulted.

The overloaded arrow operator must return a pointer to a class type or return a class type object that defines its own arrow operator.

14.7 self-increment operator and auto-decrement operator

C + + does not require self-increment to be a member of a class, but because these operators change the state of an object, it tends to be a member.

/** Smart Pointer:checks access to elements throws an out_of_range* exception if attempt to access a nonexistent element* Users allocate and free the Array*/class checkedptr {public://no default constructor; Checkedptrs must is bound to an objectcheckedptr (int *b, int *e): Beg (b), End (e), Curr (b) {}//dereference and increment Operationsprivate:int* Beg; Pointer to beginning of the arrayint* end; One past the end of the arrayint* Curr; Current position within the array};
Pre-increment/decrement (return reference to object)
Class Checkedptr {public:checkedptr& operator++ ();//Prefix Operators checkedptr& operator--(); before};//Prefix:return reference to incremented/decremented objectcheckedptr& Checkedptr::oper  ator++ () {if (Curr = = end) throw Out_of_range ("increment past the end of Checkedptr"); ++curr; Advance current state return *this;} checkedptr& checkedptr::operator--() {if (Curr = = Beg) throw Out_of_range ("decrement past the beginning of C  Heckedptr "); --curr; Move current state back one element return *this;}
Post self-increment/decrement (returns the old value of an object)

To make a difference, the postfix operator accepts an extra int parameter, which is used when the compiler provides 0 initialization of it

Class Checkedptr {public://increment and decrement checkedptr operator++ (int);//Postfix operators Checkedptr Operat  or--(int); before};//Postfix:increment/decrement Object But return unchanged valuecheckedptr Checkedptr::operat or++ (int) {//No check needed here, the call to prefix increment would do the check checkedptr ret (*this);//Save Curren T value ++*this; Advance one element, checking the increment return ret; Return saved State}
Checkedptr checkedptr::operator--(int) {//No check needed here, the call to prefix decrement would do the check CHECKEDP TR ret (*this); Save current value--*this; Move backward one element and check return ret; Return saved State}
Call
Checkedptr Parr (IA, IA + size); Iapoints to an array of intsparr.operator++ (0); Call Postfix operator++parr.operator++ (); Call prefix operator++
14.8 calling operators and Function objects

The function call operator must be declared as a member function. A class that defines the calling operator, whose objects are often called function objects, i.e. they are objects that behave like functions.

struct Absint {int operator () (int val) {return Val < 0?-val:val; }};int i = -42;absint absobj; Object, defines function call operatorunsigned int UI = Absobj (i); Calls Absint::operator (int)
Using function objects with standard library algorithms

A predicate (predicate) is a function that makes certain detections, returns the type used for conditional judgment, and indicates whether the condition is true.

Determine whether a length of a given word is 6 or Morebool GT6 (const string &s) {return s.size () >= 6;} Vector<string>::size_type WC =count_if (Words.begin (), Words.end (), GT6);

function objects can be more flexible

Determine whether a length of a given word is longer than a stored boundclass gt_cls {public:gt_cls (size_t val = 0): Bound (val) {} bool Operator () (const string &s) {return s.size () >= bound;} Private:std::string::size_type bound;};


cout << count_if (Words.begin (), Words.end (), GT_CLS (6))
<< "Words 6 characters or longer" << Endl;
function objects defined by the standard library

The standard library defines a set of arithmetic, relational, and Logical function object classes, as well as a set of function adapters that are used to customize or extend the class of function objects defined by the standard library. The standard library function object type is defined in the functional header file.

Different function objects define call operators that perform different operators; Two unary function object class:negate<type> (unary minus),logical_not<type> (logical non)

Each function object class is a template, and we need to provide a type for the template

Plus<int> Intadd; Function object that can add the int valuesnegate<int> intnegate; Function object that can negate a int value//uses intadd::operator (int, int) to add ten and 20int sum = Intadd (10, 20) ; sum = 30//uses intnegate::operator (int) to generate-10 as second parameter//to intadd::operator (int, int) sum = Intad D (Ten, Intnegate (10)); sum = 0

Function objects are often used to override the default operator used by the algorithm.

Passes temporary function object, applies > operator to, Stringssort (Svec.begin (), Svec.end (), Greater<str Ing> ());
function Adapter for function object

1) Binder (bind1st,bind2nd)

Count_if (Vec.begin (), Vec.end (), bind2nd (Less_equal<int> (), 10));

2) inverter (NOT1,NOT2)

Count_if (Vec.begin (), Vec.end (), Not1 (bind2nd (less_equal<int> (), 10));
14.9 Conversions and class types

A non-explicit constructor called by an argument defines an implicit conversion, which defines the conversion to a type. We can also define conversions from types, like other transformations, where the compiler will automatically apply this transformation.

Conversion operators

The conversion operator is a special class member function. It defines a transformation that transforms a class type into a value of another type. The conversion operator is declared in the class definition body, followed by the target type of the transformation after operator. General form:

operator type ();

1) does not allow conversions to arrays or function types, which can be converted to pointers and references;

2) The conversion function must be a member function, cannot specify a return type, but must explicitly return a value of the specified type, the formal parameter list is empty;

3) because the converted object is not changed, it is usually defined as a const member

[C++primer] [14] overloaded operators and conversions

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.