重载运算符 [] 如何工作

How does overloading operator[] work?

本文关键字:工作 何工作 运算符 重载      更新时间:2023-10-16
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;
};

我有一个问题,为什么运算符[]重载两种不同的方式。 以及它们之间有什么区别。我不知道"函数((常量"的含义。你能给我举一些例子吗?

成员函数有一个隐式参数this,尾随const用于函数重载解析。你可以这样想:

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

const 在方法上意味着该方法不允许修改对象。
第一个运算符 [] 返回对 n 处元素的引用(因此允许修改数组( - 不能在 const 对象上调用它。
第二个运算符 [] 返回 n 处元素的副本。 它不会修改数组 - 并且可以在常量对象上调用。例如:

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

这通常适用于数组作为参数传递给函数的上下文,其中它可能被限定为 const,因为它希望函数能够读取数组但不更改它。