【问题标题】:C++: Using predeclared operator[] in another method [closed]C ++:在另一种方法中使用预先声明的运算符[] [关闭]
【发布时间】:2014-11-05 23:18:28
【问题描述】:

我正在尝试在同一类的另一个方法中使用预先声明的operator[]。但是,我不知道如何进行。有趣的是,我什至不知道如何用谷歌搜索它:(。请指教...

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

代码sn-p:

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)[i]。 “你没有工作”,因为你正在使用指针索引;不是你的运营商。
  • @WhozCraig 哎呀!我认为您应该将其发布为答案而不是评论-但这实际上是解决方案...谢谢!

标签: c++ operator-overloading doubly-linked-list random-access


【解决方案1】:

尝试拨打this-&gt;operator[](i)。这应该会得到你想要的结果。

编辑

正如 WhozCraig 所说:(*this)[i] 也可以,而且可能更优雅。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多