C++:在另一个方法中使用预先声明的运算符[]

C++: Using predeclared operator[] in another method

本文关键字:声明 运算符 另一个 方法 C++      更新时间:2023-10-16

我正试图在同一类的另一个方法中使用预先声明的operator[]。但是,我不知道该怎么办。有趣的是,我甚至不知道如何在谷歌上搜索:(.请,建议…

这是一个双链接列表的一部分——我想在其中启用Array行为(我知道——不好:))。

代码片段:

template <typename T>
T& DLL<T>::operator[](int i) const{
  Node <T>*n = this->head;
  int counter = 0;
  while (counter > i) {
    n = n->next;
    counter++;
  }
  return n->next->val;
}
template <typename T>
T& DLL<T>::at(int i) const throw (IndexOutOfBounds) {
  if (i < 0 || i >= elemNum) {
    throw IndexOutOfBounds("Illegal index in function at()");
  }
  // I want this part to use the predeclared operator 
  // obviously this is not right...
  return this[i];  // Why u no work?!??!?
}

尝试调用this->operator[](i)。这应该会给你带来想要的结果。

编辑

正如WhozCraig所说:(*this)[i]同样有效,可能更优雅。