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

Overloading C++ Operators

const int& Array::operator[](int x) const

{

if (x < 0 || x >=mSize) { throw out_of_range(“”);

}

return (mElems[x]);

}

The following code demonstrates these two forms of operator[]:

#include “Array.h”

void printArray(const Array& arr, int size);

int main(int argc, char** argv)

{

Array arr; int i;

for (i = 0; i < 10; i++) {

arr[i] = 100; // Calls the non-const operator[] because // arr is a non-const object.

}

printArray(arr, 10); return (0);

}

void printArray(const Array& arr, int size)

{

for (int i = 0; i < size; i++) {

cout << arr[i] << “ “; // Calls the const operator[] because arr is a const // object.

}

cout << endl;

}

Note that the const operator[] is called in printArray() only because arr is const. If arr were not const, the non-const operator[] would be called, despite the fact that the result is not modified.

Non-Integral Array Indices

You can also write an operator[] that uses a different, non-integral, type as its index. For example, you could create an associative array, in which you use string keys instead of integers. Here is the definition for an associative array class that stores ints:

class AssociativeArray

{

public:

AssociativeArray();

~AssociativeArray();

int& operator[](const string& key);

const int& operator[](const string& key) const;

447