titus
titus

Reputation: 49

How does overloading operator[] work?

struct rowDisplayPolicy
{
  static std::string seperator() { return ", "; }
};  

struct columnDisplayPolicy
{
  static std::string seperator() { return "\n  "; }
};

template <typename T, int Size, typename DisplayPolicy>
class Array {
public:
  Array() : pArray(new T[Size]) {}
  Array(T* pT) : pArray(new T[Size])
{
    for(int i=0; i<Size; ++i)
    *(pArray + i) = *(pT + i);
}
  ~Array() { delete [] pArray; }
  T& operator[](int n)
  {
    if(n<0 || Size<=n) throw std::Exception("index out of range");
    return *(pArray+n);
  }
  T operator[](int n) const
  {
    if(n<0 || Size<=n) throw std::Exception("index out of range");
    return *(pArray+n);
  }
  void display() const
  {
    std::cout << "\n  ";
    for(int i=0; i<Size-1; ++i)
      std::cout << *(pArray+i) << DisplayPolicy::seperator();
    std::cout << *(pArray+Size-1) << "\n";
  }
private:
  Array(const Array<T,Size,DisplayPolicy>&);  // make public impl. Later
  Array<T,Size,DisplayPolicy>& operator=(const Array<T,Size,DisplayPolicy>&); // ditto
  T* pArray;
};

I have a question that, Why operator[] overloading two different ways. and What's difference between them. I don't know clear the meaning of 'function() const'. can you show me some examples.

Upvotes: 1

Views: 140

Answers (2)

K-ballo
K-ballo

Reputation: 81349

Member functions have an implicit parameter this, the trailing const is used for function overload resolution. You can think of it like this:

void Array::function() -> void function( Array* this )

void Array::function() const -> void function( Array const* this )

Upvotes: 2

Ricibob
Ricibob

Reputation: 7705

const on a method means that the method cannot allow modification of the object.
The first operator[] returns a reference to the element at n (and hence allows modification of the array) - it could not be called on objects that are const.
The second operator[] returns a copy of the element at n. It does not modify the array - and can be called on objects that are const. Eg:

Array<int, 10> my_array1();
int test1 = my_array1[0]; // Calls first operator[]

const Array<int, 10> my_array2();
int test2 = my_array2[0]; // Calls second operator equals

This would more often apply to the context where the array is passed to a function as a parameter where it maybe qualified as const because it wants the function to be able to read the array but not change it.

Upvotes: 1

Related Questions