[Error] invalid initialization of non-const reference of type ** from an rvalue of type**c++临时变量参数

前几天在写有关栈的操作时,出现了error
[Error] invalid initialization of non-const reference of type ‘ElemType& {aka int&}’ from an rvalue
相同的写法改成c没有报错,但在c++的环境下出现了问题。一时搞不清楚,在网上看了大佬的博客,发现这是c++中功能函数(如出栈)内的临时变量做了函数参数导致的。
这是函数参数引用临时变量错误,c++中临时变量不能作为非const的引用参数
解决方法:需要在函数声明和定义中在该参数的类型前添加const关键字。

例如在进栈操作时:

Status Push_Sq(SqStack &S,const ElemType &e);

在main函数中:int i;? for(i=1; i<=6; i++)? Push_Sq(S,i*4);

将i*4入栈 ,使用了临时变量i*4,故在Push_Sq函数参数前要加const。

或者使用一个作用域大于函数所在的区域的变量做参数。

发布了9 篇原创文章 · 获赞 0 · 访问量 194

猜你喜欢

转载自blog.csdn.net/zydbk123456/article/details/102669110