【发布时间】:2020-09-12 07:27:41
【问题描述】:
我正在尝试使用 cpp 中的链表实现堆栈。我正在使用类来制作链接列表,但出现以下错误,我不明白为什么
#include <bits/stdc++.h>
using namespace std;
class Stack{
public:
int top;
Stack* next;
Stack(int data){ //constructor
top = data;
next = NULL;
}
void push(Stack* &head, int data);
int pop(Stack* &head);
bool empty(Stack* &head);
};
void Stack::push(Stack* &head, int data){
Stack* s = new Stack(data);
s->next = head;
head = s;
}
int pop(Stack* &head){
int x = head->top;
head = head->next;
return x;
}
bool empty(Stack* &head){
if(head == NULL)
return true;
return false;
}
int main() {
class Stack* s = new Stack(1);
s.push(2);
s.push(3);
cout << s.empty(s) << endl;
cout << s.pop(s) << endl;
cout << s.pop(s) << endl;
cout << s.pop(s) << endl;
cout << s.empty(s) << endl;
}
错误:在's'中请求成员'push',它是指针类型'Stack*'(也许你打算使用'->'?)
在's'中请求成员'empty',它是指针类型'Stack*'(也许你打算使用'->'?)
在's'中请求成员'pop',它是指针类型'Stack*'(也许你的意思是使用'->'?)
当我使用 -> 而不是 .它表示对 Stack::empty(Stack*&) 的未定义引用和对 Stack::pop(Stack*&) 的未定义引用
编辑:我使用 -> 而不是 .并添加了 Stack:: 来弹出和清空函数,它工作但构造函数不工作
【问题讨论】:
-
第一组错误是您已修复的拼写错误。你为什么要问他们?它们不属于minimal reproducible example。第二个问题(未定义的引用)是一个常见的重复,因为您已将
pop和empty定义为全局函数(而不是成员,如push是)。
标签: c++ class linked-list stack