我正在制作一个基于链表的
错误信息:
出了什么问题,我该如何解决?
代码(愚笨的我重载了后置
Stack
。除了不知道如何为其实现“基于范围的for循环”,一切都运行良好。错误信息:
error: no match for ‘operator++’ (operand type is ‘Stack<int>::Node’)
。出了什么问题,我该如何解决?
代码(愚笨的我重载了后置
++
,现已全部更正):#include <iostream>
using namespace std;
template<typename T>
class Stack{
private:
class Node{
friend Stack;
public:
void operator++(){
this->next = this->next->next; //point to next Node
}
bool operator!=(const Node& rhs){
return !(*this == rhs);
}
T operator*(){
return this->next->elem; //return current Node elem
}
bool operator==(const Node& rhs){
return this->next == rhs.next;
}
private:
T elem;
Node* next;
};
Node* first;
int _size;
public:
Stack():_size(0){
first = nullptr;
}
void push(T item){
Node* n = new Node;
n->elem = item;
n->next = first;
first = n;
_size++;
}
T pop(){
T item = first->elem;
Node* old_first = first;
first = first->next;
delete old_first;
_size--;
return item;
}
int size(){
return _size;
}
bool empty(){
return _size == 0;
}
Node begin(){
Node n;
n.next = first;
return n;
}
Node end(){
Node m;
m.next = nullptr;
return m;
}
~Stack(){
Node* ele_to_delete;
while(first != nullptr){
ele_to_delete = first;
first = first->next;
delete ele_to_delete;
}
}
Stack(const Stack&) = delete;
Stack& operator=(const Stack&) = delete;
};
int main(){
Stack<int> ls;
ls.push(1);
ls.push(2);
ls.push(3);
for(auto s: ls){
cout << s << "|";
}
return 0;
}
list
和stack
类模板。如果您想要作为练习实现自己的类,请熟悉C++中使用的iterator概念,并在您的实现中使用它。 - n. m.