重载*作为解除引用

时间:2014-04-08 19:29:05

标签: c++

我很难尝试重载*运算符。我试图使用它来取消引用指针。我已经发布了我正在尝试使用的内容。现在当我尝试使用它时,我收到以下错误indirection requires pointer operand ('Iterator' invalid)

//用法

Iterator List::Search(int key) {
    Iterator temp(head);

    while (!temp.isNull()) {
        if (*temp == key) {
            //return temp;
            cout << *temp << endl;
        }
        temp++;
    }
    return NULL;
}

//页眉文件

class Iterator {
public:
    Iterator &operator *(const Iterator &) const;
private:
    node* pntr;
};

// CPP档案

Iterator &Iterator::operator *(const Iterator & temp) const {
    return temp.pntr;
}

1 个答案:

答案 0 :(得分:7)

一元反复数运算符不需要参数。它也不太可能返回Iterator的引用。在这种情况下,我希望它返回node的引用。请注意,通过const运算符允许对数据进行可变访问,并提供仅允许ConstIterator访问的const类型,这是惯用的:

class Iterator 
{
public:
 node& operator*() const;
 node* operator->() const;
private:
  node* pntr;
};

node& Iterator::operator*() const {
  return *pntr;
}
node* Iterator::operator->() const { return pntr; }

node& Iterator::operator*() {
  return *pntr;
}
相关问题