【发布时间】:2020-12-05 19:35:37
【问题描述】:
问题已修改
我有一个包含 add() 和 begin() 函数的列表类(如链接列表)
add() 添加到尾部的函数
begin()函数返回第一个元素(head)的地址
我试图让我的班级支持范围for(:) 所以我尝试实现begin()、end() 和operator++() 函数,但我被困在operator++() 它不起作用 (阅读下面的注释)
新增功能
问题是i 是一个节点指针,所以我不能这样做++i,它只会增加指针的地址,它不会运行operator++(),因为它不是一个节点指针一个来自 Node 结构的对象,所以当我这样做时 ++(*i) 它将运行 operator++()
#include <iostream>
using namespace std;
class List
{
struct Node
{
int info;
Node *next;
Node(int val) : info(val), next(NULL) {}
Node * operator++(){ // not working
cout << "i am alive\n";
*this = *this->next;
return this;
}
};
Node *head = NULL;
Node *tail = NULL;
public:
void add(int val) // add to tail, O(1)
{
Node *temp = new Node(val);
if (!head)
{
head = temp;
tail = temp;
return;
}
tail->next = temp;
tail = temp;
}
Node *begin()
{
return head;
}
};
int main()
{
List l;
l.add(2);
l.add(5);
l.add(10);
auto i = l.begin(); // *i is 2
++i;
cout << (*i).info; // output is 0
}
请注意: 如果我这样做,它将工作并打印 5
auto i = l.begin(); // *i is 2
i->operator++(); // will work
// ++(*i); //also will work
cout << (*i).info; // output is 5
【问题讨论】:
-
尝试用实际类型替换
auto。它在这里没有帮助 -
operator++是Node类的成员函数。i是一个Node*指针。您正在更改函数调用 -++i的等效项是i.operator++(),但您调用的是i->operator++()。但除此之外,Node类中的operator++不会更改它被调用的Node,它会返回一个Node*指针,而不是Node。 -
您可能想要创建一个迭代器类并在迭代器上使用 operator++。
-
@largest_prime_is_463035818,解决问题(删除
auto并将其替换为Node*,但这解决了问题仅我将 Node 类移到 List 类之外. -
不,它没有解决问题,它只是让它更显眼
标签: c++ oop operator-overloading