Subscript operator

Posted by Didi Setyapramana On 8:36 PM 0 komentar

Subscript operator

The subscript operator, [ ], is a binary operator which must be a member function (hence it takes only one explicit parameter, the index). The subscript operator is not limited to taking an integral index. For instance, the index for the subscript operator for the std::map template is the same as the type of the key, so it may be a string etc. The subscript operator is generally overloaded twice; as a non-constant function (for when elements are altered), and as a constant function (for when elements are only accessed).
[edit] Function call operator
The function call operator, ( ), is generally overloaded to create objects which behave like functions, or for classes that have a primary operation. The function call operator must be a member function, but has no other restrictions – it may be overloaded with any number of parameters of any type, and may return any type. A class may also have several definitions for the function call operator.
[edit] Address of, Reference, and Pointer operators
These three operators, operator&(), operator*() and operator->() can be overloaded. In general these operators are only overloaded for smart pointers, or classes which attempt to mimic the behavior of a raw pointer. The pointer operator, operator->() has the additional requirement that the result of the call to that operator, must return a pointer, or a class with an overloaded operator->(). In general A == *&A should be true.

Example 

class T {

public:

const memberFunction() const;

};



// forward declaration

class DullSmartReference;



class DullSmartPointer {

private:

T *m_ptr;

public:

DullSmartPointer(T *rhs) : m_ptr(rhs) {};

DullSmartReference operator*() const {

return DullSmartReference(*m_ptr);

}

T *operator->() const {

return m_ptr;

}

};

class DullSmartReference {

private:

T *m_ptr;

public:

DullSmartReference (T &rhs) : m_ptr(&rhs) {}

DullSmartPointer operator&() const {

return DullSmartPointer(m_ptr);

}



// conversion operator

operator T { return *m_ptr; }

};

DullSmartPointer dsp(new T);

dsp->memberFunction(); // calls T::memberFunction

T t;

DullSmartReference dsr(t);

dsp = &dsr;

t = dsr; // calls the conversion operator


These are extremely simplified examples designed to show how the operators can be overloaded and not the full details of a SmartPointer or SmartReference class. In general you won’t want to overload all three of these operators in the same class.

0 Response for the "Subscript operator"

Post a Comment