提问人:Pankaj Chauhan 提问时间:4/28/2022 更新时间:4/28/2022 访问量:45
使用带有引用变量和默认值的类构造函数时遇到问题
having trouble with class constructor with reference variable and default value
问:
我正在尝试使用链表和类实现堆栈,对于堆栈类构造函数,我将引用变量作为默认值为 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;
}
答: 暂无答案
评论
t = 20;
10 = 20;
const int &t
int t
const int t
int &d=0
是不合法的。不能将文本绑定到非常量左值引用。请改用 const 引用:.或者干脆根本不使用引用:.与 、 use 或 相同。const int &d=0
int d=0
push()
const int &t
int t
stack0():size(-1), ...
所以空堆栈的大小为 -1?stack
t