【问题标题】:error in implementing stack using linked list [duplicate]使用链表实现堆栈时出错[重复]
【发布时间】: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。第二个问题(未定义的引用)是一个常见的重复,因为您已将 popempty 定义为全局函数(而不是成员,如 push 是)。

标签: c++ class linked-list stack


【解决方案1】:

在访问指针指向的结构的数据成员时使用 ->。在您的情况下,请尝试使用 -> 而不是 . on s 中的 main 函数 () 所以,要么做

Stack s; 
s.push(1);

或者

Stack* s;
s->push(s,1);

【讨论】:

  • Stack* s; s-&gt;push(s,1); — 这是未定义的行为。
【解决方案2】:

正如错误消息所说,当您有Stack* 时,您需要使用-&gt;,而不是.,如下所示:

s->push(s, 42);
s->empty(s);
// etc

但是,您可能根本不需要 Stack*,只需使用常规的 Stack 对象即可。

此外,在类外定义的成员函数需要使用类名进行限定。所以你需要:

bool Stack::empty(Stack* &head){

代替:

bool empty(Stack* &head){

就像您已经为 Stack::push 方法所做的那样。

【讨论】:

    【解决方案3】:

    您“不小心”声明了一个指针。像这样更改您的代码

    int main()
    {
        Stack s(1);
        s.push(2);
        ...
    

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 2011-07-29
      • 2020-08-09
      • 1970-01-01
      • 2013-10-05
      • 2013-10-05
      • 1970-01-01
      相关资源
      最近更新 更多