取消引用适用于 ptr->operator*() 但不适用于 *ptr

Dereference works with ptr->operator*() but not with *ptr

我正在为列表创建一个迭代器 class。迭代器有一个取消引用运算符:

    T& operator*() const {
        return this->currentNode->data;
    }

尝试使用迭代器时:

for( ; list->begin() != list->end; (*list_iter).operator++())
{
    cout << list_iter << endl;
    cout << list_iter->operator*() << endl;
    //cout << *list_iter << endl;  //not working
}

注释行显示 "invalid operand to binary experssion ostream and MyList::iterator"。同样,如果我从 (*list_iter).operator++() 更改为 list_iter++ 或 (*list_iter)++,我会收到类似的错误。

我认为发生的事情是这样的:

int num1 = 3;
int *num2 = new int;
*num2 = 3;

在这种情况下,num1 == *num2... *num2 在功能上类似于 num1(均为整数),尽管 num2 是指向整数的指针,*num2 使其成为整数。

所以在:

MyList list1();
MyList *list2 = new MyList();

在这种情况下,我是否应该期望“*list2”与 list1 相似,就像“*num2”与 num1 相似一样? num2 是要调用解引用程序,还是尝试将 MyList 变成 MyList?

真的很难理解这里发生的事情。谢谢!

重载的 operator* 仅当您直接在您定义它的 class 的对象上使用时才会生效。它对指向此类对象的指针没有影响。如果您在指针上使用 *,它只会将其取消引用到基础对象。额外的 * 将调用重载的 operator*.

MyIterator *iter = new MyIterator();
*iter;  // This will only dereference the pointer.
**iter; // This will dereference the pointer and call your operator*.

在您的情况下,ptr->operator*() 有效,因为 -> 已经进行了第一次取消引用。相当于(*ptr).operator*().

请注意,迭代器通常按值使用,您很少会在指针后面找到它们。

你的循环完全错误。

begin() 迭代器未保存到 list_iter,而是直接与 end() 迭代器进行比较。因此,如果列表不为空,循环将永远 运行。

(*list_iter).operator++() 取消引用迭代器以访问其数据,然后对该数据而不是迭代器本身调用 operator++

cout << list_iter 没有为迭代器定义。您需要取消引用迭代器,以便输出被引用的数据:cout << *list_iter.

cout << list_iter->operator*() 取消引用迭代器以访问其数据,然后对该数据而不是迭代器本身调用 operator*

您的循环应该看起来更像这样:

for(list_iter = list->begin(); list_iter != list->end(); ++list_iter)
{
    cout << *list_iter << endl;
}

或者,在 C++11 中,您可以改用 range-for loop 并让它为您处理迭代器:

for(auto &data : *list)
{
    cout << data << endl;
}