使用带有引用变量和默认值的类构造函数时遇到问题

having trouble with class constructor with reference variable and default value

提问人:Pankaj Chauhan 提问时间:4/28/2022 更新时间:4/28/2022 访问量:45

问:

我正在尝试使用链表和类实现堆栈,对于堆栈类构造函数,我将引用变量作为默认值为 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;
    
}
C++ 链接列表 堆栈 按引用传递

评论

0赞 François Andrieux 4/28/2022
将文本分配给非常量引用是没有意义的。想象一下,如果你尝试过,这对你分配给它的文字意味着什么?它会试图做.您可以尝试使用应该有效的方法,但这里根本没有理由使用引用。只是或是你通常在这里使用的东西。t = 20;10 = 20;const int &tint tconst int t
0赞 Remy Lebeau 4/28/2022
int &d=0是不合法的。不能将文本绑定到非常量左值引用。请改用 const 引用:.或者干脆根本不使用引用:.与 、 use 或 相同。const int &d=0int d=0push()const int &tint t
0赞 fabian 4/28/2022
stack0():size(-1), ...所以空堆栈的大小为 -1?
0赞 user4581301 4/28/2022
语义:如果你应该使用链表实现堆栈,你应该将链表和堆栈分开。否则不是使用链表,而是链表。stack
0赞 Paul Sanders 4/28/2022
你为什么要通过引用?没有必要。t

答: 暂无答案