C.Plus.Plus.Primer.4th.Edition [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

C.Plus.Plus.Primer.4th.Edition [Electronic resources] - نسخه متنی

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







Chapter 14. Overloaded Operations and Conversions


CONTENTS

Section 14.1 Defining an Overloaded Operator

506

Section 14.2 Input and Output Operators

513

Section 14.3 Arithmetic and Relational Operators

517

Section 14.4 Assignment Operators

520

Section 14.5 Subscript Operator

522

Section 14.6 Member Access Operators

523

Section 14.7 Increment and Decrement Operators

526

Section 14.8 Call Operator and Function Objects

530

Section 14.9 Conversions and Class Types

535

Chapter Summary

552

Defined Terms

552

In Chapter 5 we saw that C++ defines a large number of operators and automatic conversions among the built-in types. These facilities allow programmers to write a rich set of mixed-type expressions.

C++ lets us redefine the meaning of the operators when applied to objects of class type. It also lets us define conversion operations for class types. Class-type conversions are used like the built-in conversions to implicitly convert an object of one type to another type when needed.

Chapter 13 covered the importance of the assignment operator and showed how to define the assignment operator. We first used overloaded operators in Chapter 1, when our programs used the shift operators (>> and <<) for input and output and the addition operator (+) to add two Sales_items. We'll finally see in this chapter how to define these overloaded operators.

Through operator overloading, we can redefine most of the operators from Chapter 5 to work on objects of class type. Judicious use of operator overloading can make class types as intuitive to use as the built-in types. For example, the standard library defines several overloaded operators for the container classes. These classes define the subscript operator to access data elements and * and -> to dereference container iterators. The fact that these library types have the same operators makes using them similar to using built-in arrays and pointers. Allowing programs to use expressions rather than named functions can make the programs much easier to write and read. As an example, compare


cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << endl;

to the more verbose code that would be necessary if IO used named functions:


// hypothetical expression if IO used named functions
cout.print("The sum of ").print(v1).
print(" and ").print(v2).print(" is ").
print(v1 + v2).print("\n").flush();


/ 199