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

Chapter 16

private:

// Implementation details omitted

};

We leave the implementation of this class as an exercise for the reader. You might also be interested to know that the STL map provides associative array-like functionality, including the use of operator[] with any possible type as the key.

You cannot overload the subscripting operator to take more than one parameter. If you want to provide subscripting on more than one index, you can use the function call operator.

Overloading the Function Call Operator

C++ allows you to overload the function call operator, written as operator(). If you write an operator() for your class, you can use objects of that class as if they were function pointers. You can only overload this operator as a non-static method in a class. Here is an example of a simple class with an overloaded operator() and a class method with the same behavior:

class FunctionObject

{

public:

int operator() (int inParam); // Function-call operator int aMethod(int inParam); // Normal method

};

//Implementation of overloaded function-call operator int FunctionObject::operator() (int inParam)

{

return (inParam * inParam);

}

// Implementation of normal method

int FunctionObject::aMethod(int inParam)

{

return (inParam * inParam);

}

Here is an example of code that uses the function-call operator, contrasted with the call to a normal method of the class:

int main(int argc, char** argv)

{

int x = 3, xSquared, xSquaredAgain; FunctionObject square;

xSquared = square(x); // Call the function-call operator xSquaredAgain = square.aMethod(x); // Call the normal method

}

448