Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 16

 

 

Method or

 

 

 

Name or

Global Friend

When to

 

Operator

Category

Function

Overload

Sample Prototype

 

 

 

 

 

operator delete

Memory

Method

Whenever you

void operator

operator delete[]

deallocation

recommended

overload the

delete(void* ptr)

 

routines

 

memory

throw();

 

 

 

allocation

 

 

 

 

routines

void operator

 

 

 

 

delete[](void* ptr)

 

 

 

 

throw();

operator*

Dereferencing

Method

Useful for

E& operator*()

operator->

operators

required for

smart pointers

const;

 

 

operator->

 

 

 

 

 

 

E* operator->()

 

 

Method

 

const;

 

 

recommended

 

 

 

 

for operator*

 

 

operator&

Address-of

N/A

Never

N/A

 

operator

 

 

 

operator->*

Dereference

N/A

Never

N/A

 

pointer-to-

 

 

 

 

member

 

 

 

operator,

Comma

N/A

Never

N/A

 

operator

 

 

 

operator type()

Conversion,

Method

When you

operator type()

 

or cast,

required

want to

const;

 

operators

 

provide

 

 

(separate

 

conversions

 

 

operator for

 

from your

 

 

each type)

 

class to other

 

 

 

 

types

 

 

 

 

 

 

Overloading the Arithmetic Operators

In Chapter 9, you learned how to write the binary arithmetic operators and the shorthand arithmetic assignment operators. However, you did not yet learn how to overload all of the arithmetic operators.

Overloading Unary Minus and Unary Plus

C++ has several unary arithmetic operators. Two of these are unary minus and unary plus. You’ve probably used unary minus, but you might be surprised to learn about unary plus. Here is an example of these operators using ints:

438

Overloading C++ Operators

int i, j = 4;

i = -j; // Unary minus i = +i; // Unary plus

j = +(-i); // Apply unary plus to the result of applying unary minus to i. j = -(-i); // Apply unary minus to the result of applying unary minus to i.

Unary minus negates the operand, while unary plus returns the operand directly. The result of unary plus or minus is not an lvalue: you can’t assign to it. This means you should return a const object when you overload them. However, note that you can apply unary plus or unary minus to the result of unary plus or unary minus. Because you’re applying these operations to a const temporary object, you must make operator- and operator+ themselves const; otherwise, the compiler won’t let you call them on the const temporary.

Here is an example of a SpreadsheetCell class definition with an overloaded operator-. Unary plus is usually a no-op, so this class doesn’t bother to overload it.

class SpreadsheetCell

{

public:

// Omitted for brevity. Consult Chapter 9 for details.

friend const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);

friend const SpreadsheetCell operator-(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);

friend const SpreadsheetCell operator*(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);

friend const SpreadsheetCell operator/(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);

SpreadsheetCell& operator+=(const SpreadsheetCell& rhs); SpreadsheetCell& operator-=(const SpreadsheetCell& rhs); SpreadsheetCell& operator*=(const SpreadsheetCell& rhs); SpreadsheetCell& operator/=(const SpreadsheetCell& rhs); const SpreadsheetCell operator-() const;

protected:

// Omitted for brevity. Consult Chapter 9 for details.

};

Here is the definition of the unary operator-.

const SpreadsheetCell SpreadsheetCell::operator-() const

{

SpreadsheetCell newCell(*this);

newCell.set(-mValue); // call set to update mValue and mStr

return (newCell);

}

operator- doesn’t change the operand, so this method must construct a new SpreadsheetCell with the negated value, and return a copy of it. Thus, it can’t return a reference.

Overloading Increment and Decrement

Recall that there are four ways to add one to a variable:

439

Chapter 16

i = i + 1; i += 1;

++i;

i++;

The last two are called the increment operators. The first form is prefix increment, which adds one to the variable, then returns the newly incremented value for use in the rest of the expression. The second form is postfix increment, which returns the old (nonincremented) value for use in the rest of the expression. The decrement operators function similarly.

The two possible meanings for operator++ and operator-- (prefix and postfix) present a problem when you want to overload them. When you write an overloaded operator++, for example, how do you specify whether you are overloading the prefix or the postfix version? C++ introduced a hack to allow you to make this distinction: the prefix versions of operator++ and operator-- take no arguments, while the postfix versions take one unused argument of type int.

If you want to overload these operators for your SpreadsheetCell class, the prototypes would look like this:

class SpreadsheetCell

 

{

 

public:

 

// Omitted for brevity. Consult Chapter 9

for details.

SpreadsheetCell& operator++(); // Prefix

 

const SpreadsheetCell operator++(int); //

Postfix

SpreadsheetCell& operator--(); // Prefix

 

const SpreadsheetCell operator--(int); //

Postfix

protected:

 

// Omitted for brevity. Consult Chapter 9

for details.

};

 

The C++ standard specifies that the prefix versions of increment and decrement return an lvalue, so they can’t return a const value. The return value in the prefix forms is the same as the end value of the operand, so prefix increment and decrement can return a reference to the object on which they are called. The postfix versions of increment and decrement, however, return values that are different from the end values of the operands, so they cannot return references.

Here are the implementations of these operators:

SpreadsheetCell& SpreadsheetCell::operator++()

{

set(mValue + 1); return (*this);

}

const SpreadsheetCell SpreadsheetCell::operator++(int)

{

SpreadsheetCell oldCell(*this); // Save the current value before incrementing set(mValue + 1); // Increment

return (oldCell); // Return the old value.

}

SpreadsheetCell& SpreadsheetCell::operator--()

440

Overloading C++ Operators

{

set(mValue - 1); return (*this);

}

const SpreadsheetCell SpreadsheetCell::operator--(int)

{

SpreadsheetCell oldCell(*this); // Save the current value before incrementing set(mValue - 1); // Increment

return (oldCell); // Return the old value.

}

Now you can increment and decrement your SpreadsheetCell objects to your heart’s content!

SpreadsheetCell c1, c2; c1.set(4);

c2.set(4);

c1++;

++c1;

Recall that increment and decrement also work on pointers. When you write classes that are smart pointers or iterators, you can overload operator++ and operator-- to provide pointer incrementing and decrementing. You can see this topic in action in Chapter 23, in which you learn how to write your own STL iterators.

Overloading the Bitwise and

Binar y Logical Operators

The bitwise operators are similar to the arithmetic operators, and the bitwise shorthand assignment operators are similar to the arithmetic shorthand assignment operators. However, they are significantly less common, so we do not show examples here. The table in the “Summary of Overloadable Operators” section shows sample prototypes, so you should be able to implement them easily if the need ever arises.

The logical operators are trickier. We don’t recommend overloading && and ||. These operators don’t really apply to individual types: they aggregate results of Boolean expressions. Additionally, you lose the short-circuit evaluation. Thus, it rarely makes sense to overload them for specific types.

Overloading the Inser tion and

Extraction Operators

In C++, you use operators not only for arithmetic operations, but also for reading from and writing to streams. For example, when you write ints and strings to cout you use the insertion operator, <<:

int number = 10;

cout << “The number is “ << number << endl;

When you read from streams you use the extraction operator, >>:

441

Chapter 16

int number; string str;

cin >> number >> str;

You can write insertion and extraction operators that work on your classes as well, so that you can read and write them like this:

SpreadsheetCell myCell, anotherCell, aThirdCell;

cin >> myCell >> anotherCell >> aThirdCell;

cout << myCell << “ “ << anotherCell << “ “ << aThirdCell << endl;

Before you write the insertion and extraction operators, you need to decide how you want to stream your class out and how you want to read it in. For SpreadsheetCells it makes sense to read and write strings because all doubles can be read as strings (and converted back to doubles), but not vice versa.

The object on the left of an insertion or extraction operator is the istream or ostream (such as cin or cout), not a SpreadsheetCell object. Because you can’t add a method to the istream or ostream class, you should write the insertion and extraction operators as global friend functions of the SpreadsheetCell class. The declaration of these functions in your SpreadsheetCell class looks like this:

class SpreadsheetCell

{

public:

// Omitted for brevity

friend ostream& operator<<(ostream& ostr, const SpreadsheetCell& cell);

friend istream& operator>>(istream& istr, SpreadsheetCell& cell); // Omitted for brevity

};

By making the insertion operator take a reference to an ostream as its first parameter, you allow it to be used for file output streams, string output streams, cout, and cerr. See Chapter 14 for details. Similarly, by making the extraction operator take a reference to an istream, you can make it work on file input streams, string input streams, and cin.

The second parameter to operator<< and operator>> is a reference to the SpreadsheetCell object that you want to read or write. The insertion operator doesn’t change the SpreadsheetCell it writes, so that reference can be const. The extraction operator, however, modifies the SpreadsheetCell object, requiring the argument to be a non-const reference.

Both operators return a reference to the stream they were given as their first argument so that calls to the operator can be nested. Remember that the operator syntax is shorthand for calling the global operator>> or operator<< functions explicitly. Consider this line:

cin >> myCell >> anotherCell >> aThirdCell;

It’s actually shorthand for this line:

operator>>(operator>>(operator>>(cin, myCell), anotherCell), aThirdCell);

As you can see, the return value of the first call to operator>> is used as input to the next. Thus, you must return the stream reference so that it can be used in the next nested call. Otherwise, the nesting won’t compile.

442