链表的重载运算符+

Overloading operator+ for linked lists

本文关键字:运算符 重载 链表      更新时间:2023-10-16

我是初学者,现在我正在尝试实现包含函数begin((的类链表。 该函数很好地返回列表中的第一个元素,但我试图做的是在下一个位置返回迭代器,例如如下所示:

List<int>::iterator iter2 = a.begin() + 2; // or iter2 = iter2 + 1;
cout <<iter2->data;

其中输出是垃圾,如21213123..

所以在这里我想我应该使用运算符重载+,这是我的函数:

template<class T>
Node<T>* operator+(const Node<T>& iter, const int& pos)
{
cout << "in"; for testing, but seems that doesnt even entry here
return NULL;
}

那么谁能帮我?谢谢

PS:这是类节点

template<class T>
class Node {
public:
T data;
Node* next;
Node() :data(0), next(NULL) {}
Node(T val, Node<T>* pointer = NULL) :data(val), next(pointer) {}
};

和列表类

template<class T>
class List {

public:
typedef Node<T>* iterator;
typedef const Node<T>* const_iterator;
//constructors
List() { item = NULL; counter = 0; }
explicit List(int val) :counter(1) { item = new Node<T>(val); }
~List() { // to be made 
}
//public functions
int size() { return counter; }
iterator begin() {
return item;
}
iterator end()
{
iterator last = item;
while (last->next != NULL)
{
last = last->next;
}
return last;
}
void push_front(const int& val) {
iterator newNode = new Node<T>(val, item);
item = newNode;
counter++;
}
void append(const int& val)
{
iterator newnode = new Node<T>(val);
newnode->next = NULL;
iterator last = item;
if (item == NULL)
{
item = newnode;
return;
}
while (last->next != NULL)
last = last->next;
last->next = newnode;
counter++;
}
int operator[](const int&);
private:
iterator item;
int counter;
};

让我们来看看你的begin函数:

typedef Node<T>* iterator;
iterator begin() {
...
}

此函数返回一个Node<T>*,一个指向Node<T>对象的指针。结果,当你写

list.begin() + 2;

C++将其解释为"我有一个指针,我有一个数字,所以我会将指针向前迈入适当的步数。

然后你会问 - 好吧,等一下,为什么这个超载的操作员没有被调用?

template<class T>
Node<T>* operator+(const Node<T>& iter, const int& pos) {
...
}

看看参数类型。这个函数说"如果有人试图将一个诚实善良的Node<T>对象和一个int加在一起,这就是我希望你做的。问题是代码

list.begin() + 2

不会尝试在对象和整数中添加诚实到善良Node<T>。相反,它会添加一个指向Node<T>对象的指针和一个整数。由于这些类型与您的重载运算符不匹配,它甚至不会尝试调用重载运算符。

不幸的是,在C++中,您不能在两个基元类型之间重载运算符,因此无法编写一个接受Node<T>*intoperator+版本,因此这里的修复并不像"只需让您的operator+函数接受Node<T>*"那么简单。

相反,我建议将iterator类型设置为实际的classstruct,而不是原始指针。您的迭代器可能会通过跟踪指向某处某个Node<T>的指针来工作,但从根本上说,迭代器实际上不仅仅是该指针本身。例如,您可以尝试如下操作:

template <class T>
class List {
public:
class iterator {
public:
// some other things, and
iterator operator+ (int step) const;
private:
// some other things, and
Node<T>* current;
};
// some other things, and
iterator begin();
};

现在,您可以在List<T>::iterator类型上重载operator+。然后,operator+的实现可以更新迭代器中存储的Node<T>*

希望这有帮助!

链表的iterator不能是指针,它需要 像这样:

struct iterator
{   
typedef int difference_type;
typedef T* pointer;
typedef T& reference;
typedef iterator_category std::bidirectional_iterator_tag
iterator();
iterator& operator++();
iterator& operator--();
iterator operator++(int);
iterator operator--(int);
T& operator*();
T* operator->();
bool operator==(iterator rhs) const;
bool operator!=(iterator rhs) const;
private:
iterator(Node*);
Node* node;
};