与参考变量和默认值的类构造函数遇到麻烦

发布于 2025-01-24 22:31:09 字数 1060 浏览 2 评论 0原文

我正在尝试使用链接列表和类实现堆栈,并且在堆栈类构造函数上,我将参考变量作为具有默认值0的参数。但是,当我使用整数字面的推动操作时,它显示出错误。如何也可以使用默认值和参考变量来实现它?


// ***** Stack using linked list ****

#include <iostream>
using namespace std;

class node{

    node* next;
    int data;

    public:

    node(int &d=0,node* n=NULL):data(d),next(n){}
    node(){}
    ~ node(){}

    friend class stack0;
  
};

class stack0{
   
    int size;
    node* head;

    public:
    
    stack0(){}
    stack0():size(-1),head( new node() ){}

    void push(int &t){
        if (size == -1){
            head->data=t;
            cout<<"& pushed "<<t<<" at "<<head<<" with size "<<size;
            size++;
        }
        else{
            node* temp;temp=head;
            head = new node(t,head);
            cout<<"& pushed "<<t<<" at "<<head<<" with size "<<size;
            head->next=temp;
            size++;
        }
    }
};

int  main(){
    stack0 s;
    s.push(10);
    return 0;
    
}

I am trying to implement stack using linked list and class, and to the stack class constructor, I am giving reference variables as arguments with default value 0. But it shows an error when I do push operation with an integer literal. How can I implement it by using a default value and reference variable as well?


// ***** Stack using linked list ****

#include <iostream>
using namespace std;

class node{

    node* next;
    int data;

    public:

    node(int &d=0,node* n=NULL):data(d),next(n){}
    node(){}
    ~ node(){}

    friend class stack0;
  
};

class stack0{
   
    int size;
    node* head;

    public:
    
    stack0(){}
    stack0():size(-1),head( new node() ){}

    void push(int &t){
        if (size == -1){
            head->data=t;
            cout<<"& pushed "<<t<<" at "<<head<<" with size "<<size;
            size++;
        }
        else{
            node* temp;temp=head;
            head = new node(t,head);
            cout<<"& pushed "<<t<<" at "<<head<<" with size "<<size;
            head->next=temp;
            size++;
        }
    }
};

int  main(){
    stack0 s;
    s.push(10);
    return 0;
    
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文